<?php

namespace App\Jobs\Import;

use App\Events\SendWebSocketMessageEvent;
use App\Services\ImportService;
use Exception;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

class ImportCatalog implements ShouldQueue, ShouldBeUniqueUntilProcessing
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct(private readonly string $path, private readonly int $year, private readonly int $userId)
    {
        //
    }

    /**
     * @return void
     */
    public function handle(): void
    {
        try {
            (new ImportService)->handle($this->path, $this->year);
            Log::info('ImportCatalog job done!');
            event(new SendWebSocketMessageEvent('Импорт завершён!', $this->userId, ['year' => $this->year, 'path' => $this->path]));
        } catch (Exception $e) {
            Log::info('ImportCatalog job failed!');
            event(new SendWebSocketMessageEvent('Ошибка импорта! ' . $e->getMessage(), $this->userId, ['error' => $e->getMessage()]));
        }
    }
}
