package token

import (
	"time"

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

type patchOpts struct {
	ID        string     `json:"id"  src:"path@token_id" desc:"令牌ID"`
	ExpiredAt *time.Time `json:"expired_at"  src:"json" desc:"过期时间"`
	OverPerm  *string    `json:"over_perm"  src:"json" desc:"覆盖权限"`
}

var _ = Router.Patch("/{token_id}", "更新 Token", tokenPatch)

func tokenPatch(x *vigo.X, opts *patchOpts) (*models.Token, error) {
	data := &models.Token{}

	err := cfg.DB().Where("id = ?", opts.ID).First(data).Error
	if err != nil {
		return nil, err
	}
	optsMap := make(map[string]interface{})
	if opts.ExpiredAt != nil {
		optsMap["expired_at"] = opts.ExpiredAt
	}
	if opts.OverPerm != nil {
		optsMap["over_perm"] = opts.OverPerm
	}
	err = cfg.DB().Model(data).Updates(optsMap).Error

	return data, err
}

type deleteOpts struct {
	ID string `src:"path@token_id" desc:"令牌ID"`
}

var _ = Router.Delete("/{token_id}", "删除 Token", tokenDelete)

func tokenDelete(x *vigo.X, opts *deleteOpts) (*models.Token, error) {
	data := &models.Token{}
	err := cfg.DB().Where("id = ?", opts.ID).Delete(data).Error
	return data, err
}
