<?php

namespace App\Jobs;

use App\Domain\Import\ImportPipeline;
use App\Models\MarkdownImport;
use App\Models\PreQuestionCandidate;
use App\Models\SourceFile;
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\Str;

class ProcessPdfJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(public readonly string $path)
    {
    }

    public function handle(ImportPipeline $pipeline): void
    {
        $sourceFile = SourceFile::create([
            'uuid' => (string) Str::uuid(),
            'original_filename' => basename($this->path),
            'normalized_filename' => basename($this->path),
            'extension' => 'pdf',
            'storage_path' => $this->path,
            'raw_markdown' => '',
            'source_type' => 'pdf',
            'filename' => basename($this->path),
            'path' => $this->path,
            'status' => 'pending',
        ]);

        $import = MarkdownImport::create([
            'file_name' => $sourceFile->original_filename ?: $sourceFile->filename ?: 'pdf',
            'original_markdown' => '',
            'source_type' => 'pdf',
            'source_name' => $this->path,
            'status' => MarkdownImport::STATUS_PROCESSING,
            'progress_stage' => MarkdownImport::STAGE_SPLITTING,
        ]);

        $payload = $pipeline->run('pdf', [
            'path' => $this->path,
        ]);

        foreach ($payload['blocks'] ?? [] as $block) {
            PreQuestionCandidate::create([
                'import_id' => $import->id,
                'source_file_id' => $sourceFile->id,
                'order_index' => (int) ($block['sequence'] ?? 0),
                'index' => (int) ($block['index'] ?? 0),
                'raw_markdown' => (string) ($block['raw_markdown'] ?? ''),
                'raw_text' => '',
                'is_question_candidate' => false,
                'status' => PreQuestionCandidate::STATUS_PENDING,
                'meta' => $block['meta'] ?? [],
            ]);
        }
    }
}
