package handlers

import (
	"context"
	"net/http"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"

	"yh_web/server/config"
	"yh_web/server/models"

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

const paymentConfigDocID = "payment"

// GetPaymentConfig 获取支付配置（仅 role_id=9527, role=admin）
func GetPaymentConfig(c *gin.Context) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	coll := config.GetDB(config.DBName).Collection("system_config")
	var cfg models.PaymentConfig
	err := coll.FindOne(ctx, bson.M{"_id": paymentConfigDocID}).Decode(&cfg)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			c.JSON(http.StatusOK, models.PaymentConfig{})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, cfg)
}

// PaymentConfigUpdateInput 支付配置更新
type PaymentConfigUpdateInput struct {
	Wechat *WechatPayUpdateInput `json:"wechat"`
	Alipay *AlipayUpdateInput    `json:"alipay"`
}

type WechatPayUpdateInput struct {
	AppID    string `json:"app_id"`
	MchID    string `json:"mch_id"`
	APIKey   string `json:"api_key"`
	APIKeyV3 string `json:"api_key_v3"`
	Enabled  *bool  `json:"enabled"`
}

type AlipayUpdateInput struct {
	AppID           string `json:"app_id"`
	PrivateKey      string `json:"private_key"`
	AlipayPublicKey string `json:"alipay_public_key"`
	Enabled         *bool  `json:"enabled"`
}

// UpdatePaymentConfig 更新支付配置
func UpdatePaymentConfig(c *gin.Context) {
	var input PaymentConfigUpdateInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	coll := config.GetDB(config.DBName).Collection("system_config")
	set := bson.M{}

	if input.Wechat != nil {
		w := bson.M{}
		if input.Wechat.AppID != "" {
			w["app_id"] = input.Wechat.AppID
		}
		if input.Wechat.MchID != "" {
			w["mch_id"] = input.Wechat.MchID
		}
		if input.Wechat.APIKey != "" {
			w["api_key"] = input.Wechat.APIKey
		}
		if input.Wechat.APIKeyV3 != "" {
			w["api_key_v3"] = input.Wechat.APIKeyV3
		}
		if input.Wechat.Enabled != nil {
			w["enabled"] = *input.Wechat.Enabled
		}
		for k, v := range w {
			set["wechat."+k] = v
		}
	}

	if input.Alipay != nil {
		a := bson.M{}
		if input.Alipay.AppID != "" {
			a["app_id"] = input.Alipay.AppID
		}
		if input.Alipay.PrivateKey != "" {
			a["private_key"] = input.Alipay.PrivateKey
		}
		if input.Alipay.AlipayPublicKey != "" {
			a["alipay_public_key"] = input.Alipay.AlipayPublicKey
		}
		if input.Alipay.Enabled != nil {
			a["enabled"] = *input.Alipay.Enabled
		}
		for k, v := range a {
			set["alipay."+k] = v
		}
	}

	if len(set) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无有效更新字段"})
		return
	}

	opts := options.UpdateOne().SetUpsert(true)
	_, err := coll.UpdateOne(ctx, bson.M{"_id": paymentConfigDocID}, bson.M{"$set": set}, opts)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "配置已保存"})
}
