package pay

import (
	"context"
	"strings"
	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/common/xerr"

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

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

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

func (l *PaymentCheckLogic) PaymentCheck(req *types.PaymentCheckReq) (resp *types.PaymentCheckResp, err error) {
	// 根据订单号前缀判断订单类型
	if strings.HasPrefix(req.OrderNo, "U_") {
		// 升级订单
		order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询升级订单失败: %v", err)
		}
		return &types.PaymentCheckResp{
			Type:   "agent_upgrade",
			Status: order.Status,
		}, nil
	}
	
	// 查询订单（包括代理订单）
	order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单失败: %v", err)
	}
	return &types.PaymentCheckResp{
		Type:   "query",
		Status: order.Status,
	}, nil
}
