package pay

import (
	"context"
	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/lzUtils"
	"time"

	"github.com/pkg/errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type IapCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewIapCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IapCallbackLogic {
	return &IapCallbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *IapCallbackLogic) IapCallback(req *types.IapCallbackReq) error {
	// Step 1: 查找订单
	order, findOrderErr := l.svcCtx.OrderModel.FindOne(l.ctx, req.OrderID)
	if findOrderErr != nil {
		logx.Errorf("苹果内购支付回调，查找订单失败: %+v", findOrderErr)
		return nil
	}

	// Step 2: 验证订单状态
	if order.Status != "pending" {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 订单状态异常: %+v", order)
	}

	// Step 3: 调用 VerifyReceipt 验证苹果支付凭证
	//receipt := req.TransactionReceipt // 从请求中获取支付凭证
	//verifyResponse, verifyErr := l.svcCtx.ApplePayService.VerifyReceipt(l.ctx, receipt)
	//if verifyErr != nil {
	//	return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 验证订单异常: %+v", verifyErr)
	//}

	// Step 4: 验证订单
	//product, findProductErr := l.svcCtx.ProductModel.FindOne(l.ctx, order.Id)
	//if findProductErr != nil {
	//	return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "苹果内购支付回调, 获取订单相关商品失败: %+v", findProductErr)
	//}
	//isProductMatched := false
	//appleProductID := l.svcCtx.ApplePayService.GetIappayAppID(product.ProductEn)
	//for _, item := range verifyResponse.Receipt.InApp {
	//	if item.ProductID == appleProductID {
	//		isProductMatched = true
	//		order.PlatformOrderId = lzUtils.StringToNullString(item.TransactionID) // 记录交易 ID
	//		break
	//	}
	//}
	//if !isProductMatched {
	//	return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 商品 ID 不匹配，订单 ID: %d, 回调苹果商品 ID: %s", order.Id, verifyResponse.Receipt.InApp[0].ProductID)
	//}

	// Step 5: 更新订单状态 mm
	order.Status = "paid"
	order.PayTime = lzUtils.TimeToNullTime(time.Now())

	// 更新订单到数据库
	if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 修改订单信息失败: %+v", updateErr)
	}

	// Step 6: 处理订单完成后的逻辑
	if asyncErr := l.svcCtx.AsynqService.SendQueryTask(order.Id); asyncErr != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调,异步任务调度失败: %v", asyncErr)
	}
	return nil
}
