//
// create.go
// Copyright (C) 2024 veypi <i@veypi.com>
// Distributed under terms of the MIT license.
//

package access

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

type createOpts struct {
	AppID      string  `json:"app_id" src:"json" desc:"应用ID"`
	UserID     *string `json:"user_id" src:"json" desc:"用户ID"`
	RoleID     *string `json:"role_id" src:"json" desc:"角色ID"`
	ResourceID *string `json:"resource_id" src:"json" desc:"资源ID"`
	Name       string  `json:"name" src:"json" desc:"名称"`
	TID        string  `json:"tid" src:"json" desc:"资源ID"`
	Level      uint    `json:"level" src:"json" desc:"级别"`
}

var _ = Router.Post("/", "创建访问权限", createAccess)

func createAccess(x *vigo.X, opts *createOpts) (*models.Access, error) {
	// 创建新记录
	access := models.Access{
		AppID:      opts.AppID,
		UserID:     opts.UserID,
		RoleID:     opts.RoleID,
		ResourceID: opts.ResourceID,
		Name:       opts.Name,
		TID:        opts.TID,
		Level:      opts.Level,
	}

	// 保存到数据库
	if err := cfg.DB().Create(&access).Error; err != nil {
		return nil, err
	}

	return &access, nil
}
