package wechat

import (
	"fmt"

	"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel"
	"github.com/ArtisanCloud/PowerWeChat/v3/src/officialAccount"
	"github.com/ArtisanCloud/PowerWeChat/v3/src/payment"
	"github.com/break/junhong_cmp_fiber/pkg/config"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
)

// NewRedisCache 使用项目现有的 Redis 客户端创建 PowerWeChat 的 Redis Cache
func NewRedisCache(rdb *redis.Client) kernel.CacheInterface {
	return kernel.NewRedisClient(&kernel.UniversalOptions{
		Addrs:    []string{rdb.Options().Addr},
		Password: rdb.Options().Password,
		DB:       rdb.Options().DB,
	})
}

// NewOfficialAccountApp 创建微信公众号应用实例
func NewOfficialAccountApp(cfg *config.Config, cache kernel.CacheInterface, logger *zap.Logger) (*officialAccount.OfficialAccount, error) {
	oaCfg := cfg.Wechat.OfficialAccount
	if oaCfg.AppID == "" || oaCfg.AppSecret == "" {
		return nil, fmt.Errorf("微信公众号配置不完整：缺少 AppID 或 AppSecret")
	}

	userConfig := &officialAccount.UserConfig{
		AppID:  oaCfg.AppID,
		Secret: oaCfg.AppSecret,
		Cache:  cache,
	}

	// 可选配置：消息验证 Token 和 AESKey
	if oaCfg.Token != "" {
		userConfig.Token = oaCfg.Token
	}
	if oaCfg.AESKey != "" {
		userConfig.AESKey = oaCfg.AESKey
	}

	app, err := officialAccount.NewOfficialAccount(userConfig)
	if err != nil {
		logger.Error("创建微信公众号应用失败", zap.Error(err))
		return nil, fmt.Errorf("创建微信公众号应用失败: %w", err)
	}

	logger.Info("微信公众号应用初始化成功", zap.String("app_id", oaCfg.AppID))
	return app, nil
}

// NewPaymentApp 创建微信支付应用实例
func NewPaymentApp(cfg *config.Config, cache kernel.CacheInterface, logger *zap.Logger) (*payment.Payment, error) {
	payCfg := cfg.Wechat.Payment
	if payCfg.AppID == "" || payCfg.MchID == "" {
		return nil, fmt.Errorf("微信支付配置不完整：缺少 AppID 或 MchID")
	}

	userConfig := &payment.UserConfig{
		AppID:       payCfg.AppID,
		MchID:       payCfg.MchID,
		MchApiV3Key: payCfg.APIV3Key,
		Key:         payCfg.APIV2Key,
		CertPath:    payCfg.CertPath,
		KeyPath:     payCfg.KeyPath,
		SerialNo:    payCfg.SerialNo,
		NotifyURL:   payCfg.NotifyURL,
		HttpDebug:   payCfg.HttpDebug,
		Cache:       cache,
	}

	app, err := payment.NewPayment(userConfig)
	if err != nil {
		logger.Error("创建微信支付应用失败", zap.Error(err))
		return nil, fmt.Errorf("创建微信支付应用失败: %w", err)
	}

	logger.Info("微信支付应用初始化成功",
		zap.String("app_id", payCfg.AppID),
		zap.String("mch_id", payCfg.MchID),
	)
	return app, nil
}
