package query

import (
	"context"
	"in-server/common/ctxdata"
	"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 QueryDetailByOrderNoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *QueryDetailByOrderNoLogic) QueryDetailByOrderNo(req *types.QueryDetailByOrderNoReq) (resp string, err error) {
	// 获取当前用户ID
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
	}

	// 获取订单信息
	order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
	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.UserId != userId {
		isAgent, aerr := IsOrderAgent(l.ctx, l.svcCtx, userId, order.Id)
		if aerr != nil {
			return "", aerr
		}
		if !isAgent {
			return "", errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "无权查看此订单报告")
		}
	}

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

	queryModel, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, order.Id)
	if err != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
	}
	respStr, buildErr := BuildEncryptedQuery(l.ctx, l.svcCtx, queryModel)
	if buildErr != nil {
		return "", buildErr
	}
	return respStr, nil
}
