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(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(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(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(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(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(id, req); err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}

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

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 IsNotFound(err):
		response.Error(c, http.StatusNotFound, "not_found", "管理员不存在")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "管理员管理服务暂时不可用")
	}
}
