package adminmgr

import (
	"errors"
	"net/http"
	"strconv"

	"hfb_sys/backend/internal/middleware"
	"hfb_sys/backend/pkg/response"

	"github.com/gin-gonic/gin"
)

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

func (h *Handler) List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	result, err := h.service.List(c.Request.Context(), page, pageSize)
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) FindByID(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.FindByID(c.Request.Context(), id)
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Create(c *gin.Context) {
	var req CreateAdminRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "用户名和密码不能为空")
		return
	}
	item, err := h.service.Create(c.Request.Context(), req)
	if err != nil {
		writeError(c, err)
		return
	}
	response.Created(c, item)
}

func (h *Handler) Update(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req UpdateAdminRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求格式不正确")
		return
	}
	item, err := h.service.Update(c.Request.Context(), id, req)
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Delete(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	currentAdminID, _ := c.Get(middleware.ContextAdminID)
	if err := h.service.Delete(c.Request.Context(), id, currentAdminID.(uint64)); err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, gin.H{"deleted": true})
}

func (h *Handler) AssignRoles(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req AssignRolesRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求格式不正确")
		return
	}
	if err := h.service.AssignRoles(c.Request.Context(), id, req); err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}

func (h *Handler) ChangePassword(c *gin.Context) {
	h.ChangeOwnPassword(c)
}

func (h *Handler) ChangeOwnPassword(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	var req ChangePasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "密码不能为空")
		return
	}
	if err := h.service.ChangeOwnPassword(c.Request.Context(), adminID, req); err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}

func (h *Handler) ResetPassword(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req ResetPasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "密码不能为空")
		return
	}
	if err := h.service.ResetPassword(c.Request.Context(), id, req); err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}

func currentAdminID(c *gin.Context) (uint64, bool) {
	value, ok := c.Get(middleware.ContextAdminID)
	if !ok {
		return 0, false
	}
	adminID, ok := value.(uint64)
	return adminID, ok
}

func parseID(c *gin.Context) (uint64, bool) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil || id == 0 {
		response.BadRequest(c, "ID 不正确")
		return 0, false
	}
	return id, true
}

func writeError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrCannotDeleteSelf):
		response.BadRequest(c, "不能删除自己的账号")
	case errors.Is(err, ErrLastSuperAdmin):
		response.BadRequest(c, "不能删除最后一个超级管理员")
	case errors.Is(err, ErrWrongPassword):
		response.BadRequest(c, "原密码错误")
	case errors.Is(err, ErrWeakPassword):
		response.BadRequest(c, "密码至少 8 位且需包含字母和数字")
	case IsNotFound(err):
		response.Error(c, http.StatusNotFound, "not_found", "管理员不存在")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "管理员管理服务暂时不可用")
	}
}
