package realname

import (
	"errors"
	"net/http"

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

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

type Handler struct {
	service *Service
}

type StartRealnameRequest struct {
	Name string `json:"name" binding:"required"`
	IDNo string `json:"id_no" binding:"required"`
}

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

func (h *Handler) Start(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}

	var req StartRealnameRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "姓名和身份证号不能为空")
		return
	}

	record, err := h.service.Start(c.Request.Context(), userID, req.Name, req.IDNo)
	if err != nil {
		writeRealnameError(c, err)
		return
	}
	response.OK(c, ToPublicStatus(record))
}

func (h *Handler) Status(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}

	status, err := h.service.Status(userID)
	if err != nil {
		writeRealnameError(c, err)
		return
	}
	response.OK(c, status)
}

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

func writeRealnameError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrInvalidRealnameInput):
		response.BadRequest(c, "姓名或身份证号格式不正确")
	case errors.Is(err, ErrProviderConfigInvalid):
		response.ServiceUnavailable(c, "实名认证服务未配置")
	case errors.Is(err, ErrProviderRateLimited):
		response.Error(c, http.StatusTooManyRequests, "realname_rate_limited", "实名认证请求过于频繁，请稍后再试")
	case errors.Is(err, ErrProviderUnavailable):
		response.Error(c, http.StatusBadGateway, "realname_provider_unavailable", "实名认证服务调用失败，请稍后再试")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "实名认证服务暂时不可用")
	}
}
