package query

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

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

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

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

func (l *ConfirmQueryStateLogic) ConfirmQueryState(req *types.ConfirmQueryStateReq) (resp *types.ConfirmQueryStateResp, err error) {
	// 1. 通过 order_id 查询订单，判断订单是否已支付
	order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.OrderID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单失败: %v", err)
	}
	if order == nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "订单不存在")
	}
	// 若订单未支付，则直接返回 OrderState := "pending", QueryState := ""
	if order.Status != model.OrderStatusPaid {
		return &types.ConfirmQueryStateResp{
			OrderState: order.Status,
			QueryState: "",
		}, nil
	}

	// 2. 订单已支付，查询 query 状态（假设通过 order_id 查询 query 记录，例如使用 QueryModel.FindOneByOrderId）
	query, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, req.OrderID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询 query 失败: %v", err)
	}
	if query == nil {
		// 若 query 不存在，则返回 OrderState := "paid", QueryState := ""
		return &types.ConfirmQueryStateResp{
			OrderState: order.Status,
			QueryState: "",
		}, nil
	}
	// 否则，返回 OrderState := "paid", QueryState := query.QueryState
	return &types.ConfirmQueryStateResp{
		OrderState: query.QueryState,
		QueryState: query.QueryState,
	}, nil
}
