package admin

import (
	"net/http"
	"time"

	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
	adminsvc "bindbox-game/internal/service/admin"
)

type userListRequest struct {
	UserName   string `form:"userName"`
	UserGender string `form:"userGender"`
	UserPhone  string `form:"userPhone"`
	UserEmail  string `form:"userEmail"`
	Status     string `form:"status"`
	Current    int    `form:"current"`
	Size       int    `form:"size"`
}

type userListItem struct {
	ID         int32    `json:"id"`
	Avatar     string   `json:"avatar"`
	Status     string   `json:"status"`
	UserName   string   `json:"userName"`
	UserGender string   `json:"userGender"`
	NickName   string   `json:"nickName"`
	UserPhone  string   `json:"userPhone"`
	UserEmail  string   `json:"userEmail"`
	UserRoles  []string `json:"userRoles"`
	CreateBy   string   `json:"createBy"`
	CreateTime string   `json:"createTime"`
	UpdateBy   string   `json:"updateBy"`
	UpdateTime string   `json:"updateTime"`
}

type userListResponse struct {
	Records []userListItem `json:"records"`
	Current int            `json:"current"`
	Size    int            `json:"size"`
	Total   int64          `json:"total"`
}

// ListUsers 系统用户列表（映射到 Admin 表）
// @Summary 系统用户列表
// @Description 返回系统用户分页数据
// @Tags 管理端.系统
// @Accept json
// @Produce json
// @Param current query int true "页码" default(1)
// @Param size query int true "每页数量" default(20)
// @Param userName query string false "用户名"
// @Param userEmail query string false "邮箱"
// @Param userPhone query string false "手机号"
// @Param status query string false "状态"
// @Success 200 {object} userListResponse
// @Router /api/user/list [get]
// @Security LoginVerifyToken
func (h *handler) ListUsers() 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, 10001, validation.Error(err)))
			return
		}
		if req.Current <= 0 {
			req.Current = 1
		}
		if req.Size <= 0 {
			req.Size = 20
		}

		q := h.readDB.Admin.WithContext(ctx.RequestContext()).ReadDB()
		if req.UserName != "" {
			q = q.Where(h.readDB.Admin.Username.Like("%" + req.UserName + "%"))
		}
		if req.UserEmail != "" {
			// 注意：Admin模型没有邮箱字段，这里用昵称字段来支持搜索
			q = q.Where(h.readDB.Admin.Nickname.Like("%" + req.UserEmail + "%"))
		}
		if req.UserPhone != "" {
			q = q.Where(h.readDB.Admin.Mobile.Like("%" + req.UserPhone + "%"))
		}
		if req.Status != "" {
			// 状态筛选：1-正常 0-禁用
			if req.Status == "1" || req.Status == "正常" {
				q = q.Where(h.readDB.Admin.LoginStatus.Eq(1))
			} else if req.Status == "0" || req.Status == "禁用" {
				q = q.Where(h.readDB.Admin.LoginStatus.Eq(0))
			}
		}

		total, err := q.Count()
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10002, err.Error()))
			return
		}

		admins, err := q.Offset((req.Current - 1) * req.Size).Limit(req.Size).Find()
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10003, err.Error()))
			return
		}

		res.Records = make([]userListItem, len(admins))
		for i, a := range admins {
			res.Records[i] = userListItem{
				ID:         a.ID,
				Avatar:     a.Avatar,
				Status:     mapLoginStatus(a.LoginStatus),
				UserName:   a.Username,
				UserGender: "未知",
				NickName:   a.Nickname,
				UserPhone:  a.Mobile,
				UserEmail:  "",
				UserRoles:  rolesFromAdmin(a.IsSuper),
				CreateBy:   a.CreatedUser,
				CreateTime: a.CreatedAt.Format(time.RFC3339),
				UpdateBy:   a.UpdatedUser,
				UpdateTime: a.UpdatedAt.Format(time.RFC3339),
			}
		}
		res.Current = req.Current
		res.Size = req.Size
		res.Total = total
		ctx.Payload(res)
	}
}

func mapLoginStatus(s int32) string {
	switch s {
	case 1:
		return "1"
	case 0:
		return "4"
	default:
		return "2"
	}
}

func rolesFromAdmin(isSuper int32) []string {
	if isSuper == 1 {
		return []string{"R_SUPER"}
	}
	return []string{"R_ADMIN"}
}

type createUserRequest struct {
	Username string `json:"username" binding:"required"`
	Nickname string `json:"nickname"`
	Mobile   string `json:"mobile"`
	Password string `json:"password" binding:"required"`
	Avatar   string `json:"avatar"`
}

type createUserResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

// CreateUser 创建系统用户（管理员）
// @Summary 创建系统用户
// @Description 创建新的管理员账号
// @Tags 管理端.系统
// @Accept json
// @Produce json
// @Param RequestBody body createUserRequest true "请求参数"
// @Success 200 {object} createUserResponse
// @Failure 400 {object} code.Failure
// @Router /api/user [post]
// @Security LoginVerifyToken
func (h *handler) CreateUser() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createUserRequest)
		res := new(createUserResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10001, validation.Error(err)))
			return
		}

		createdBy := ctx.SessionUserInfo().UserName

		if err := h.svc.Create(ctx.RequestContext(), adminsvc.CreateInput{
			Username:  req.Username,
			Nickname:  req.Nickname,
			Mobile:    req.Mobile,
			Password:  req.Password,
			Avatar:    req.Avatar,
			CreatedBy: createdBy,
		}); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10002, err.Error()))
			return
		}

		res.Success = true
		res.Message = "创建成功"
		ctx.Payload(res)
	}
}
