package resource

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

type updateOpts struct {
	ResourceID string  `src:"path@resource_id" desc:"资源ID"`
	Name       *string `json:"name" src:"json" desc:"资源名称"`
	Des        *string `json:"des" src:"json" desc:"资源描述"`
}

var _ = Router.Patch("/{resource_id}", "更新资源", updateResource)

func updateResource(x *vigo.X, opts *updateOpts) (*models.Resource, error) {
	// 查找资源
	resource := &models.Resource{}
	if err := cfg.DB().Where("id = ?", opts.ResourceID).First(resource).Error; err != nil {
		return nil, vigo.NewError("resource not found").WithCode(404)
	}

	// 更新字段
	updates := map[string]interface{}{}
	if opts.Name != nil {
		updates["name"] = *opts.Name
	}
	if opts.Des != nil {
		updates["des"] = *opts.Des
	}

	// 执行更新
	if len(updates) > 0 {
		if err := cfg.DB().Model(resource).Updates(updates).Error; err != nil {
			return nil, vigo.NewError("failed to update resource").WithCode(500)
		}
	}
	return resource, nil
}
