package app

import (
	"strings"

	"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	wechatConfigSvc "github.com/break/junhong_cmp_fiber/internal/service/wechat_config"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/logger"
	"github.com/break/junhong_cmp_fiber/pkg/response"
	"github.com/break/junhong_cmp_fiber/pkg/wechat"
	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
)

var clientWechatValidator = validator.New()

// ClientWechatHandler C 端微信相关处理器
type ClientWechatHandler struct {
	wechatConfigService *wechatConfigSvc.Service
	wechatCache         kernel.CacheInterface
	logger              *zap.Logger
}

// NewClientWechatHandler 创建 C 端微信处理器
func NewClientWechatHandler(
	wechatConfigService *wechatConfigSvc.Service,
	rdb *redis.Client,
	log *zap.Logger,
) *ClientWechatHandler {
	var cache kernel.CacheInterface
	if rdb != nil {
		cache = wechat.NewRedisCache(rdb)
	}
	return &ClientWechatHandler{
		wechatConfigService: wechatConfigService,
		wechatCache:         cache,
		logger:              log,
	}
}

// GetJSSDKConfig 获取微信 JSSDK 签名配置
// GET /api/c/v1/wechat/jssdk-config
func (h *ClientWechatHandler) GetJSSDKConfig(c *fiber.Ctx) error {
	var req dto.JSSDKConfigRequest
	if err := c.QueryParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	if err := clientWechatValidator.Struct(&req); err != nil {
		logger.GetAppLogger().Warn("获取 JSSDK 配置参数校验失败", zap.Error(err))
		return errors.New(errors.CodeInvalidParam)
	}

	wechatConfig, err := h.wechatConfigService.GetActiveConfig(c.UserContext())
	if err != nil {
		return err
	}

	oaApp, err := wechat.NewOfficialAccountAppFromConfig(wechatConfig, h.wechatCache, h.logger)
	if err != nil {
		h.logger.Error("初始化微信公众号应用失败", zap.Error(err))
		return errors.New(errors.CodeWechatConfigUnavailable)
	}

	oaService := wechat.NewOfficialAccountService(oaApp, h.logger)
	jssdkConfig, err := oaService.GetJSSDKConfig(c.UserContext(), req.URL)
	if err != nil {
		return err
	}

	return response.Success(c, &dto.JSSDKConfigResponse{
		AppID:     jssdkConfig.AppID,
		Timestamp: jssdkConfig.Timestamp,
		NonceStr:  jssdkConfig.NonceStr,
		Signature: jssdkConfig.Signature,
	})
}

// GetAppID 获取当前生效的公众号 AppID
// GET /api/c/v1/wechat/appid
func (h *ClientWechatHandler) GetAppID(c *fiber.Ctx) error {
	wechatConfig, err := h.wechatConfigService.GetActiveConfig(c.UserContext())
	if err != nil {
		return err
	}
	if wechatConfig == nil || strings.TrimSpace(wechatConfig.OaAppID) == "" {
		return errors.New(errors.CodeWechatConfigUnavailable)
	}

	return response.Success(c, &dto.WechatAppIDResponse{
		AppID: wechatConfig.OaAppID,
	})
}
