package frontend

import (
	"encoding/json"
	"fmt"
	"io"
	"time"
	"verification-platform-backend/internal/database"
	"verification-platform-backend/internal/model"
	"verification-platform-backend/internal/service/payment"

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

func SetupPaymentCallbackRoutes(r *gin.Engine) {
	r.POST("/api/v1/payment/callback/bepusdt", handleBEpusdtCallback)
}

func handleBEpusdtCallback(c *gin.Context) {
	body, err := io.ReadAll(c.Request.Body)
	if err != nil {
		c.String(200, "fail")
		return
	}

	var callbackData payment.CallbackData
	if err := json.Unmarshal(body, &callbackData); err != nil {
		c.String(200, "fail")
		return
	}

	var order model.Order
	if err := database.DB.Where("order_no = ?", callbackData.OrderID).First(&order).Error; err != nil {
		c.String(200, "fail")
		return
	}

	if order.Status != "pending" {
		c.String(200, "success")
		return
	}

	var extraData struct {
		TradeID        string `json:"trade_id"`
		ChannelID      uint   `json:"channel_id"`
		ExpirationTime string `json:"expiration_time"`
	}
	if order.ExtraData != "" {
		json.Unmarshal([]byte(order.ExtraData), &extraData)
	}

	if extraData.ExpirationTime != "" {
		expirationTime, err := time.Parse(time.RFC3339, extraData.ExpirationTime)
		if err == nil && time.Now().After(expirationTime) {
			c.String(200, "fail")
			return
		}
	}

	var paymentChannel model.PaymentChannel
	if extraData.ChannelID > 0 {
		database.DB.First(&paymentChannel, extraData.ChannelID)
	}

	if paymentChannel.ID > 0 {
		paymentService, err := payment.GetPaymentService(paymentChannel, "")
		if err == nil {
			if !paymentService.VerifyCallback(callbackData) {
				c.String(200, "fail")
				return
			}
		}
	}

	if callbackData.Status == 2 {
		now := time.Now()
		order.Status = "paid"
		order.PaymentAt = &now
		order.PaymentMethod = "bepusdt"

		if err := database.DB.Save(&order).Error; err != nil {
			c.String(200, "fail")
			return
		}

		if order.OrderType == "package" {
			var pkg model.Package
			if err := database.DB.First(&pkg, order.PackageID).Error; err == nil {
				var expiredAt *time.Time
				if pkg.Period != "" && pkg.Period != "permanent" {
					duration := parsePeriod(pkg.Period)
					if duration > 0 {
						exp := now.Add(duration)
						expiredAt = &exp
					}
				}

				userPackage := model.UserPackage{
					UserID:    order.UserID,
					PackageID: pkg.ID,
					ExpiredAt: expiredAt,
					Status:    "active",
				}

				if err := database.DB.Create(&userPackage).Error; err != nil {
					fmt.Printf("创建套餐授权失败: %v\n", err)
				} else {
					database.DB.Model(&model.User{}).Where("id = ?", order.UserID).Update("current_package_id", pkg.ID)
				}
			}
		}
	}

	c.String(200, "success")
}
