package app

import (
	"fmt"
	"net/http"

	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/timeutil"
	"mini-chat/internal/pkg/validation"

	"gorm.io/gorm"
)

type userListRequest struct {
	AppID    string `form:"app_id"`    // 小程序ID
	UserID   string `form:"user_id"`   // 用户ID
	UserName string `form:"user_name"` // 用户昵称
	Page     int    `form:"page"`      // 当前页码，默认为第一页
	PageSize int    `form:"page_size"` // 每页返回的数据量
}

type userListData struct {
	UserID     string `json:"user_id"`     // 用户ID
	UserName   string `json:"user_name"`   // 用户昵称
	UserMobile string `json:"user_mobile"` // 用户手机号
	UserAvatar string `json:"user_avatar"` // 用户头像
	CreatedAt  string `json:"created_at"`  // 创建时间
}

type userListResponse struct {
	Page     int            `json:"page"`      // 当前页码
	PageSize int            `json:"page_size"` // 每页返回的数据量
	Total    int64          `json:"total"`     // 符合查询条件的总记录数
	List     []userListData `json:"list"`
}

// UserPageList 小程序用户列表
// @Summary 小程序用户列表
// @Description 小程序用户列表
// @Tags 管理端.小程序
// @Accept json
// @Produce json
// @Param app_id query string true "小程序ID"
// @Param user_name query string false "用户昵称"
// @Param user_id query string false "用户ID"
// @Param page query int true "当前页码" default(1)
// @Param page_size query int true "每页返回的数据量，最多 100 条" default(20)
// @Success 200 {object} userListResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/app/users [get]
// @Security LoginVerifyToken
func (h *handler) UserPageList() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(userListRequest)
		res := new(userListResponse)

		if err := ctx.ShouldBindForm(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				validation.Error(err)),
			)
			return
		}

		if req.Page == 0 {
			req.Page = 1
		}

		if req.PageSize == 0 {
			req.PageSize = 20
		}

		if req.PageSize > 100 {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ListAppUserError,
				fmt.Sprintf("%s: 一次最多只能查询 100 条", code.Text(code.ListAppUserError)),
			))
			return
		}

		query := h.readDB.AppUser.WithContext(ctx.RequestContext()).Where(h.readDB.AppUser.AppID.Eq(req.AppID))

		if req.UserID != "" {
			query = query.Where(h.readDB.AppUser.UserID.Eq(req.UserID))
		}

		if req.UserName != "" {
			query = query.Where(h.readDB.AppUser.UserName.Like(fmt.Sprintf("%%%s%%", req.UserName)))
		}

		listQueryDB := query.Session(&gorm.Session{})
		countQueryDB := query.Session(&gorm.Session{})

		resultData, err := listQueryDB.
			Order(h.readDB.AppUser.ID.Desc()).
			Limit(req.PageSize).
			Offset((req.Page - 1) * req.PageSize).Find()
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ListAppUserError,
				fmt.Sprintf("%s：%s", code.Text(code.ListAppUserError), err.Error())),
			)
			return
		}

		count, err := countQueryDB.Count()
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ListAppUserError,
				fmt.Sprintf("%s：%s", code.Text(code.ListAppUserError), err.Error())),
			)
			return
		}

		res.Page = req.Page
		res.PageSize = req.PageSize
		res.Total = count
		res.List = make([]userListData, len(resultData))

		for k, v := range resultData {
			res.List[k] = userListData{
				UserID:     v.UserID,
				UserName:   v.UserName,
				UserMobile: v.UserMobile,
				UserAvatar: v.UserAvatar,
				CreatedAt:  timeutil.FriendlyTime(v.CreatedAt),
			}
		}

		ctx.Payload(res)
	}
}
