<?php

namespace App\Jobs;

use App\Modules\ImageSync\ImageSync;
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\App;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Enums\QueueProcessType;
use Mtc\MercuryDataModels\QueueProcessLog;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private readonly string $syncServiceClass)
    {
        $this->onQueue('bulk-media');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(): void
    {
        $syncService = App::make($this->syncServiceClass);

        if (!$syncService instanceof ImageSync) {
            Log::error("RunImageSyncTask: {$this->syncServiceClass} does not implement ImageSync");
            return;
        }

        $processLog = QueueProcessLog::start(
            QueueProcessType::ImageSync,
            $this->syncServiceClass,
            ['tenant' => tenant('id')]
        );

        try {
            $syncService->sync();
            $processLog->markCompleted();
        } catch (\Exception $exception) {
            $processLog->markFailed($exception->getMessage(), [
                'exception_class' => get_class($exception),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => array_slice($exception->getTrace(), 0, 10),
            ]);

            Log::error($exception->getMessage());
        }
    }
}
