<?php

namespace App\Jobs;

use App\Imports\Blog\Contracts\BlogFileParser;
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;
use Illuminate\Support\Facades\Storage;

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

    public int $timeout = 600;

    /**
     * @param string $filePath Path to the uploaded file on file-storage disk
     * @param class-string<BlogFileParser> $parserClass Fully qualified parser class name
     * @param array<string, mixed> $parserConfig Configuration passed to the parser constructor
     */
    public function __construct(
        private readonly string $filePath,
        private readonly string $parserClass,
        private readonly array $parserConfig = [],
    ) {
        //
    }

    public function handle(): void
    {
        $fileContents = Storage::disk('file-storage')->get($this->filePath);

        if (!$fileContents) {
            Log::error('BlogImportJob: File not found', ['path' => $this->filePath]);
            return;
        }

        /** @var BlogFileParser $parser */
        $parser = new $this->parserClass(...$this->parserConfig);
        $articles = $parser->parse($fileContents);

        $count = 0;
        foreach ($articles as $article) {
            BaseArticleImport::dispatch($article);
            $count++;
        }

        Log::info('BlogImportJob: Dispatched ' . $count . ' article import jobs', [
            'path' => $this->filePath,
            'parser' => $this->parserClass,
        ]);

        Storage::disk('file-storage')->delete($this->filePath);
    }
}
