<?php

namespace App\Jobs;

use App\Models\Paper;
use App\Services\ExamPdfExportService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * 单个试卷 PDF 重新生成任务（用于批量重生成 API 的队列）
 */
class RegeneratePdfJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public string $paperId;

    public ?bool $includeKpExplain;

    public int $tries = 2;

    public int $timeout = 300;

    public function __construct(string $paperId, ?bool $includeKpExplain = null)
    {
        $this->paperId = $paperId;
        $this->includeKpExplain = $includeKpExplain;

        $this->onQueue('pdf');
    }

    public function handle(ExamPdfExportService $pdfExportService): void
    {
        $paper = Paper::with('questions')->find($this->paperId);
        if (! $paper || $paper->questions->isEmpty()) {
            Log::warning('RegeneratePdfJob: 跳过无题目试卷', ['paper_id' => $this->paperId]);

            return;
        }

        $useKpExplain = $this->includeKpExplain ?? ($paper->paper_type !== 0);

        try {
            Log::info('RegeneratePdfJob: 开始', ['paper_id' => $this->paperId]);
            $pdfUrl = $pdfExportService->generateUnifiedPdf($this->paperId, $useKpExplain);
            if ($pdfUrl) {
                Log::info('RegeneratePdfJob: 成功', ['paper_id' => $this->paperId, 'pdf_url' => $pdfUrl]);
            } else {
                Log::warning('RegeneratePdfJob: 返回空', ['paper_id' => $this->paperId]);
            }
        } catch (\Exception $e) {
            Log::error('RegeneratePdfJob: 异常', [
                'paper_id' => $this->paperId,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }
}
