package query

import (
	"context"
	"in-server/common/xerr"
	"github.com/pkg/errors"

	"in-server/app/main/api/internal/svc"
	"in-server/app/main/api/internal/types"
	"in-server/app/main/model"

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

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

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

func (l *QueryDetailByOrderIdPublicLogic) QueryDetailByOrderIdPublic(req *types.QueryDetailByOrderIdReq) (resp string, err error) {
	// 公共接口：仅校验订单存在且已支付，不做用户绑定校验，用于【生成 PDF】等内部场景

	// 获取订单信息
	order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.OrderId)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return "", errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询(公共), 订单不存在: %v", err)
		}
		return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询(公共), 查找订单错误: %v", err)
	}

	// 检查订单状态：未支付则不返回报告
	if order.Status != "paid" {
		return "", errors.Wrapf(xerr.NewErrMsg("订单未支付，无法查看报告"), "")
	}

	// 查找对应查询记录并构建加密响应，复用已有工具函数
	queryModel, qErr := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, req.OrderId)
	if qErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询(公共), 查找报告错误: %v", qErr)
	}

	respStr, buildErr := BuildEncryptedQuery(l.ctx, l.svcCtx, queryModel)
	if buildErr != nil {
		return "", buildErr
	}

	return respStr, nil
}
