package admin

import (
    "net/http"
    "strconv"
    "time"

    "bindbox-game/internal/pkg/core"
    "bindbox-game/internal/pkg/validation"
    "bindbox-game/internal/repository/mysql/model"
)

type roleListRequest struct {
	RoleId      int64  `form:"roleId"`
	RoleName    string `form:"roleName"`
	RoleCode    string `form:"roleCode"`
	Description string `form:"description"`
	Enabled     *bool  `form:"enabled"`
	Current     int    `form:"current"`
	Size        int    `form:"size"`
}

type roleItem struct {
	RoleId      int64  `json:"roleId"`
	RoleName    string `json:"roleName"`
	RoleCode    string `json:"roleCode"`
	Description string `json:"description"`
	Enabled     bool   `json:"enabled"`
	CreateTime  string `json:"createTime"`
}

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

// ListRoles 角色列表
// @Summary 角色列表
// @Tags 管理端.系统
// @Accept json
// @Produce json
// @Param current query int true "页码" default(1)
// @Param size query int true "每页数量" default(20)
// @Param roleName query string false "角色名称"
// @Param roleCode query string false "角色编码"
// @Param enabled query bool false "是否启用"
// @Success 200 {object} roleListResponse
// @Router /api/role/list [get]
// @Security LoginVerifyToken
func (h *handler) ListRoles() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(roleListRequest)
		res := new(roleListResponse)
		if err := ctx.ShouldBindForm(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10011, validation.Error(err)))
			return
		}
		if req.Current <= 0 {
			req.Current = 1
		}
		if req.Size <= 0 {
			req.Size = 20
		}
		q := h.readDB.Roles.WithContext(ctx.RequestContext()).ReadDB()
		if req.RoleName != "" {
			q = q.Where(h.readDB.Roles.RoleName.Like("%" + req.RoleName + "%"))
		}
		if req.RoleCode != "" {
			q = q.Where(h.readDB.Roles.RoleCode.Like("%" + req.RoleCode + "%"))
		}
		if req.Enabled != nil {
			q = q.Where(h.readDB.Roles.Enabled.Is(*req.Enabled))
		}
		total, err := q.Count()
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10012, err.Error()))
			return
		}
		rows, err := q.Offset((req.Current - 1) * req.Size).Limit(req.Size).Find()
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10013, err.Error()))
			return
		}
		res.Records = make([]roleItem, len(rows))
		for i, r := range rows {
			res.Records[i] = roleItem{
				RoleId:      r.ID,
				RoleName:    r.RoleName,
				RoleCode:    r.RoleCode,
				Description: r.Description,
				Enabled:     r.Enabled,
				CreateTime:  r.CreatedAt.Format("2006-01-02 15:04:05"),
			}
		}
		res.Current = req.Current
		res.Size = req.Size
		res.Total = total
		ctx.Payload(res)
	}
}

type createRoleRequest struct {
	RoleName    string `json:"roleName" binding:"required"`
	RoleCode    string `json:"roleCode" binding:"required"`
	Description string `json:"description"`
	Enabled     bool   `json:"enabled"`
}

func (h *handler) CreateRole() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createRoleRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10014, validation.Error(err)))
			return
		}
		err := h.writeDB.Roles.WithContext(ctx.RequestContext()).Create(&model.Roles{RoleName: req.RoleName, RoleCode: req.RoleCode, Description: req.Description, Enabled: req.Enabled})
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10015, err.Error()))
			return
		}
		ctx.Payload(map[string]string{"message": "ok"})
	}
}

type modifyRoleRequest struct {
	RoleName    *string `json:"roleName"`
	Description *string `json:"description"`
	Enabled     *bool   `json:"enabled"`
}

func (h *handler) ModifyRole() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(modifyRoleRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10016, validation.Error(err)))
			return
		}
		idStr := ctx.Param("role_id")
		id, _ := strconv.ParseInt(idStr, 10, 64)
		updater := h.writeDB.Roles.WithContext(ctx.RequestContext()).Where(h.writeDB.Roles.ID.Eq(id))
		set := map[string]any{}
		if req.RoleName != nil {
			set["role_name"] = *req.RoleName
		}
		if req.Description != nil {
			set["description"] = *req.Description
		}
		if req.Enabled != nil {
			set["enabled"] = *req.Enabled
		}
		if len(set) == 0 {
			ctx.Payload(map[string]string{"message": "ok"})
			return
		}
		if _, err := updater.Updates(set); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10017, err.Error()))
			return
		}
		ctx.Payload(map[string]string{"message": "ok"})
	}
}

func (h *handler) DeleteRole() core.HandlerFunc {
    return func(ctx core.Context) {
        idStr := ctx.Param("role_id")
        id, _ := strconv.ParseInt(idStr, 10, 64)
        uid := int64(ctx.SessionUserInfo().Id)
        set := map[string]any{"deleted_at": time.Now(), "deleted_by": uid}
        if _, err := h.writeDB.Roles.WithContext(ctx.RequestContext()).Where(h.writeDB.Roles.ID.Eq(id)).Updates(set); err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, 10018, err.Error()))
            return
        }
        ctx.Payload(map[string]string{"message": "ok"})
    }
}

type assignUsersRequest struct {
	AdminIDs []int64 `json:"admin_ids" binding:"required"`
}

func (h *handler) AssignRoleUsers() core.HandlerFunc {
	return func(ctx core.Context) {
		idStr := ctx.Param("role_id")
		id, _ := strconv.ParseInt(idStr, 10, 64)
		req := new(assignUsersRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10019, validation.Error(err)))
			return
		}
		tx := h.writeDB.RoleUsers.WithContext(ctx.RequestContext())
		for _, uid := range req.AdminIDs {
			err := tx.Create(&model.RoleUsers{RoleID: id, AdminID: int32(uid)})
			if err != nil {
				ctx.AbortWithError(core.Error(http.StatusBadRequest, 10020, err.Error()))
				return
			}
		}
		ctx.Payload(map[string]string{"message": "ok"})
	}
}

func (h *handler) ListRoleUsers() core.HandlerFunc {
	return func(ctx core.Context) {
		idStr := ctx.Param("role_id")
		id, _ := strconv.ParseInt(idStr, 10, 64)
		rows, err := h.readDB.RoleUsers.WithContext(ctx.RequestContext()).Where(h.readDB.RoleUsers.RoleID.Eq(id)).Find()
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10022, err.Error()))
			return
		}
		ctx.Payload(rows)
	}
}

func (h *handler) RemoveRoleUser() core.HandlerFunc {
    return func(ctx core.Context) {
        roleIDStr := ctx.Param("role_id")
        adminIDStr := ctx.Param("admin_id")
        roleID, _ := strconv.ParseInt(roleIDStr, 10, 64)
        adminID, _ := strconv.ParseInt(adminIDStr, 10, 64)
        uid := int64(ctx.SessionUserInfo().Id)
        set := map[string]any{"deleted_at": time.Now(), "deleted_by": uid}
        _, err := h.writeDB.RoleUsers.WithContext(ctx.RequestContext()).Where(h.writeDB.RoleUsers.RoleID.Eq(roleID), h.writeDB.RoleUsers.AdminID.Eq(int32(adminID))).Updates(set)
        if err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, 10023, err.Error()))
            return
        }
        ctx.Payload(map[string]string{"message": "ok"})
    }
}
