package query

import (
	"context"
	"fmt"

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

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

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

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

func (l *DownloadReportPdfLogic) DownloadReportPdf(req *types.DownloadReportPdfReq) (resp *types.DownloadReportPdfResp, err error) {
	orderId := req.OrderId

	// 若没有传 orderId 但有 orderNo，则先根据订单号查出订单ID，确保 PDF 渲染页能走按 orderId 的公开接口
	if orderId == "" && req.OrderNo != "" {
		order, findErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
		if findErr != nil {
			if errors.Is(findErr, model.ErrNotFound) {
				logx.Errorf("生成报告 PDF 失败, 未找到订单, orderNo=%s, err=%v", req.OrderNo, findErr)
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询, 订单不存在: %v", findErr)
			}
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找订单错误: %v", findErr)
		}
		// 仅允许已支付订单生成报告 PDF
		if order.Status != "paid" {
			return nil, errors.Wrapf(xerr.NewErrMsg("订单未支付，无法生成报告 PDF"), "")
		}
		orderId = order.Id
	}

	pdfBytes, err := l.svcCtx.ReportPDFService.GetOrGenerateReportPDF(l.ctx, orderId, req.OrderNo)
	if err != nil {
		logx.Errorf("生成报告 PDF 失败, orderId=%s, orderNo=%s, err=%v", orderId, req.OrderNo, err)
		return nil, fmt.Errorf("生成报告 PDF 失败: %w", err)
	}

	resp = &types.DownloadReportPdfResp{
		FileName: fmt.Sprintf("report_%s.pdf", req.OrderNo),
		Content:  pdfBytes,
	}
	return resp, nil
}
