<?php

namespace App\Jobs\Export;

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

class ExportCatalog implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct(private readonly array $filters, private readonly int $userId)
    {
        // can add where clauses
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            $file = (new ExportService())->handle($this->filters);
            Log::info('ExportCatalog job done!');
            event(new SendWebSocketMessageEvent('Экспорт завершён!', $this->userId, ['download' => $file]));
        } catch (Exception $e) {
            Log::info('ExportCatalog job failed!');
            event(new SendWebSocketMessageEvent('Ошибка экспорта! ' . $e->getMessage(), $this->userId, ['error' => $e->getMessage()]));
        }
    }
}
