package callback

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	wecominfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/wecom"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
)

// WeComApprovalHandler 提供企业微信审批加密回调入口。
type WeComApprovalHandler struct {
	service *wecominfra.CallbackService
}

// NewWeComApprovalHandler 创建企业微信审批回调 Handler。
func NewWeComApprovalHandler(service *wecominfra.CallbackService) *WeComApprovalHandler {
	return &WeComApprovalHandler{service: service}
}

// Verify 验证企业微信审批回调 URL。
// GET /api/callback/wecom/approval/:application_id
func (h *WeComApprovalHandler) Verify(c *fiber.Ctx) error {
	applicationID, err := parseWeComApplicationID(c.Params("application_id"))
	if err != nil {
		return err
	}
	plaintext, err := h.service.VerifyURL(
		c.UserContext(), applicationID, c.Query("msg_signature"), c.Query("timestamp"), c.Query("nonce"), c.Query("echostr"),
	)
	if err != nil {
		return err
	}
	c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
	return c.Send(plaintext)
}

// Receive 接收企业微信审批状态变化事件并快速返回 success。
// POST /api/callback/wecom/approval/:application_id
func (h *WeComApprovalHandler) Receive(c *fiber.Ctx) error {
	applicationID, err := parseWeComApplicationID(c.Params("application_id"))
	if err != nil {
		return err
	}
	if err := h.service.Receive(
		c.UserContext(), applicationID, c.Query("msg_signature"), c.Query("timestamp"), c.Query("nonce"), c.Body(),
	); err != nil {
		return err
	}
	c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
	return c.SendString("success")
}

func parseWeComApplicationID(value string) (uint, error) {
	id, err := strconv.ParseUint(value, 10, 64)
	if err != nil || id == 0 {
		return 0, errors.New(errors.CodeInvalidParam, "企业微信应用配置 ID 无效")
	}
	return uint(id), nil
}
