// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.

package org

import (
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/models"
	"github.com/veypi/vigo"
)

type PatchRequest struct {
	OrgID       string  `src:"path@org_id" desc:"组织ID"`
	Name        *string `json:"name,omitempty" src:"json" desc:"组织名称"`
	Description *string `json:"description,omitempty" src:"json" desc:"描述"`
	Logo        *string `json:"logo,omitempty" src:"json" desc:"Logo"`
}

func patch(x *vigo.X, req *PatchRequest) (*models.Org, error) {
	var org models.Org
	if err := cfg.DB().First(&org, "id = ?", req.OrgID).Error; err != nil {
		return nil, vigo.ErrNotFound
	}

	updates := make(map[string]any)
	if req.Name != nil {
		updates["name"] = *req.Name
	}
	if req.Description != nil {
		updates["description"] = *req.Description
	}
	if req.Logo != nil {
		updates["logo"] = *req.Logo
	}

	if err := cfg.DB().Model(&org).Updates(updates).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	return &org, nil
}
