package role

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

type ListReq struct {
	Page     int     `json:"page" src:"query" default:"1" desc:"页码"`
	PageSize int     `json:"page_size" src:"query" default:"20" desc:"每页数量"`
	Scope    *string `json:"scope" src:"query" desc:"Scope"`
	Keyword  *string `json:"keyword" src:"query" desc:"Search Keyword"`
}

type ListResp struct {
	Items      []models.Role `json:"items"`
	Total      int64         `json:"total"`
	Page       int           `json:"page"`
	PageSize   int           `json:"page_size"`
	TotalPages int           `json:"total_pages"`
}

func list(x *vigo.X, req *ListReq) (*ListResp, error) {
	db := cfg.DB().Model(&models.Role{})

	if req.Scope != nil && *req.Scope != "" {
		db = db.Where("scope = ?", *req.Scope)
	}

	if req.Keyword != nil && *req.Keyword != "" {
		db = db.Where("name LIKE ? OR code LIKE ?", "%"+*req.Keyword+"%", "%"+*req.Keyword+"%")
	}

	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	var roles []models.Role
	offset := (req.Page - 1) * req.PageSize
	if err := db.Order("created_at DESC").Offset(offset).Limit(req.PageSize).Find(&roles).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	totalPages := int(total) / req.PageSize
	if int(total)%req.PageSize > 0 {
		totalPages++
	}

	return &ListResp{
		Items:      roles,
		Total:      total,
		Page:       req.Page,
		PageSize:   req.PageSize,
		TotalPages: totalPages,
	}, nil
}
