//
// get.go
// Copyright (C) 2025 veypi <i@veypi.com>
// 2025-05-09 17:24
// Distributed under terms of the MIT license.
//

package token

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

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

var _ = Router.Get("/{token_id}", "获取 Token 详情", tokenGet)

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

type listOpts struct {
	Limit  int    `json:"limit" src:"query" desc:"限制数量"`
	UserID string `json:"user_id" gorm:"index;type:varchar(36)"  src:"query" desc:"用户ID"`
	AppID  string `json:"app_id" gorm:"index;type:varchar(36)"  src:"query" desc:"应用ID"`
}

var _ = Router.Get("/", "获取 Token 列表", tokenList)

func tokenList(x *vigo.X, opts *listOpts) ([]*models.Token, error) {
	data := make([]*models.Token, 0, 10)

	query := cfg.DB()
	if opts.UserID != "" {
		query = query.Where("user_id = ?", opts.UserID)
	}
	if opts.AppID != "" {
		query = query.Where("app_id = ?", opts.AppID)
	}
	err := query.Limit(opts.Limit).Find(&data).Error
	return data, err
}
