package role

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

var _ = Router.Get("/", "获取角色列表", listRoles)

type listOpts struct {
	AppID    string `src:"path@app_id" desc:"应用ID"`
	Page     int    `src:"query" default:"1" desc:"页码"`
	PageSize int    `src:"query" default:"20" desc:"页大小"`
	Keyword  string `src:"query" default:"" desc:"关键词"`
	SortBy   string `src:"query" default:"created_at" desc:"排序字段"`
	Order    string `src:"query" default:"desc" desc:"排序方向"`
}

type listResponse struct {
	Total int64          `json:"total"`
	Items []*models.Role `json:"items"`
}

func listRoles(x *vigo.X, opts *listOpts) (*listResponse, error) {
	// 构建查询
	db := cfg.DB().Model(&models.Role{}).Where("app_id = ?", opts.AppID)
	query := db

	// 应用关键词搜索
	if opts.Keyword != "" {
		query = query.Where("name LIKE ? OR des LIKE ?", "%"+opts.Keyword+"%", "%"+opts.Keyword+"%")
	}

	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页和排序
	offset := (opts.Page - 1) * opts.PageSize
	query = query.Order(opts.SortBy + " " + opts.Order)
	query = query.Offset(offset).Limit(opts.PageSize)

	// 查询数据
	var roles []*models.Role
	if err := query.Find(&roles).Error; err != nil {
		return nil, err
	}

	// 返回结果
	return &listResponse{
		Total: total,
		Items: roles,
	}, nil
}
