//
// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
//

package user

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

// ListRequest 用户列表请求
type ListRequest struct {
	Page     int    `json:"page" src:"query" default:"1" desc:"页码"`
	PageSize int    `json:"page_size" src:"query" default:"20" desc:"每页数量"`
	Keyword  *string `json:"keyword" src:"query" desc:"搜索关键词"`
	Status   *int    `json:"status" src:"query" desc:"状态筛选"`
}

// ListResponse 列表响应
type ListResponse struct {
	Items      []models.User `json:"items"`
	Total      int64         `json:"total"`
	Page       int           `json:"page"`
	PageSize   int           `json:"page_size"`
	TotalPages int           `json:"total_pages"`
}

// list 用户列表
func list(x *vigo.X, req *ListRequest) (*ListResponse, error) {
	db := cfg.DB().Model(&models.User{})

	// 搜索关键词
	if req.Keyword != nil && *req.Keyword != "" {
		db = db.Where("username LIKE ? OR nickname LIKE ? OR email LIKE ?",
			"%"+*req.Keyword+"%", "%"+*req.Keyword+"%", "%"+*req.Keyword+"%")
	}

	// 状态筛选
	if req.Status != nil {
		db = db.Where("status = ?", *req.Status)
	}

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

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

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

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