package query

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

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

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

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

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

func (l *QueryDetailByOrderIdLogic) QueryDetailByOrderId(req *types.QueryDetailByOrderIdReq) (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.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)
	}
	user, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)
	if err != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找用户错误: %v", err)
	}
    if user.Inside != 1 {
        // 安全验证：确保订单属于当前用户，或为该订单的代理
        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, req.OrderId)
    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
}
