package paymentaccount

import (
	"hfb_sys/backend/pkg/response"
	"strconv"

	"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) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	result, err := h.service.List(c.Request.Context(), userID, page, pageSize)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, result)
}

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

	id, ok := parseID(c)
	if !ok {
		return
	}

	account, err := h.service.FindByID(c.Request.Context(), userID, id)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, account)
}

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

	var req CreatePaymentAccountRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误")
		return
	}

	account, err := h.service.Create(c.Request.Context(), userID, req)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, account)
}

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

	id, ok := parseID(c)
	if !ok {
		return
	}

	var req UpdatePaymentAccountRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误")
		return
	}

	account, err := h.service.Update(c.Request.Context(), userID, id, req)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, account)
}

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

	id, ok := parseID(c)
	if !ok {
		return
	}

	if err := h.service.Delete(c.Request.Context(), userID, id); err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, gin.H{"deleted": true})
}

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

	id, ok := parseID(c)
	if !ok {
		return
	}

	if err := h.service.SetDefault(c.Request.Context(), userID, id); err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, gin.H{"updated": true})
}

// 辅助函数
func currentUserID(c *gin.Context) (uint64, bool) {
	val, exists := c.Get("user_id")
	if !exists {
		return 0, false
	}
	userID, ok := val.(uint64)
	return userID, ok
}

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

func writeError(c *gin.Context, err error) {
	switch err {
	case ErrAccountNotFound:
		response.NotFound(c, "收款账号不存在")
	case ErrAccountNameMismatch:
		response.BadRequest(c, "账户名必须与实名认证姓名一致")
	case ErrRealnameRequired:
		response.BadRequest(c, "请先完成实名认证")
	case ErrAccountLimit:
		response.BadRequest(c, "收款账号数量已达上限（最多5个）")
	case ErrCannotDeleteDefault:
		response.BadRequest(c, "无法删除默认账号")
	default:
		response.InternalServerError(c, "操作失败")
	}
}
