package resource

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"`
	Name     string `src:"query" desc:"资源名称"`
}

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

var _ = Router.Get("/", "获取资源列表", listResources)

func listResources(x *vigo.X, opts *listOpts) (*listResponse, error) {
	// 构建查询
	db := cfg.DB().Model(&models.Resource{})
	if opts.AppID != "" {
		db = db.Where("app_id = ?", opts.AppID)
	}
	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 resources []*models.Resource
	if err := db.Offset(offset).Limit(opts.PageSize).Find(&resources).Error; err != nil {
		return nil, err
	}

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