<?php

namespace App\Jobs;

use App\Models\Question;
use App\Models\QuestionAsset;
use App\Services\SvgConverterService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public function __construct(public readonly int $questionId)
    {
    }

    public function handle(SvgConverterService $service): void
    {
        $question = Question::find($this->questionId);
        if (!$question) {
            return;
        }

        $assets = $service->extractSvgAssets($question->stem ?? '');

        foreach ($assets as $asset) {
            QuestionAsset::firstOrCreate([
                'question_id' => $question->id,
                'asset_type' => $asset['type'] ?? 'svg',
                'path' => $asset['path'] ?? '',
            ], [
                'meta' => $asset['meta'] ?? [],
            ]);
        }
    }
}
