package adminrole

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

	"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) {
	items, err := h.service.List()
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, items)
}

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 CreateRoleRequest
	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 UpdateRoleRequest
	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
	}
	if err := h.service.Delete(id); err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, gin.H{"deleted": true})
}

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

func (h *Handler) ListPermissions(c *gin.Context) {
	items, err := h.service.ListPermissions()
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, items)
}

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, ErrProtectedRole):
		response.BadRequest(c, "该角色为系统内置角色，不可删除")
	case IsNotFound(err):
		response.Error(c, http.StatusNotFound, "not_found", "角色不存在")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "角色管理服务暂时不可用")
	}
}
