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

package access

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

type listOpts struct {
	Page     int    `src:"query" desc:"页码" default:"1"`
	PageSize int    `src:"query" desc:"每页大小" default:"20"`
	AppID    string `src:"query" desc:"应用ID"`
	UserID   string `src:"query" desc:"用户ID"`
	RoleID   string `src:"query" desc:"角色ID"`
	Name     string `src:"query" desc:"名称"`
}

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

var _ = Router.Get("/", "获取访问权限列表", listAccess)

func listAccess(x *vigo.X, opts *listOpts) (*listResponse, error) {
	// 构建查询
	db := cfg.DB().Model(&models.Access{})
	if opts.AppID != "" {
		db = db.Where("app_id = ?", opts.AppID)
	}
	if opts.UserID != "" {
		db = db.Where("user_id = ?", opts.UserID)
	}
	if opts.RoleID != "" {
		db = db.Where("role_id = ?", opts.RoleID)
	}
	if opts.Name != "" {
		db = db.Where("name LIKE ?", "%"+opts.Name+"%")
	}

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

	// 分页查询
	offset := (opts.Page - 1) * opts.PageSize
	var items []models.Access
	if err := db.Offset(offset).Limit(opts.PageSize).Find(&items).Error; err != nil {
		return nil, err
	}

	return &listResponse{
		Total: total,
		Items: items,
	}, nil
}
