<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Artwork;
use App\Services\Vision\VectorService;
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;

final class SyncArtworkVectorIndexJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $tries = 3;

    public int $timeout = 30;

    public function __construct(private readonly int $artworkId)
    {
        $queue = (string) config('recommendations.queue', config('vision.queue', 'default'));
        if ($queue !== '') {
            $this->onQueue($queue);
        }
    }

    public function backoff(): array
    {
        return [2, 10, 30];
    }

    public function handle(VectorService $vectors): void
    {
        if (! $vectors->isConfigured()) {
            return;
        }

        $artwork = Artwork::query()
            ->with(['categories' => fn ($categories) => $categories->with('contentType')->orderBy('sort_order')->orderBy('name')])
            ->find($this->artworkId);

        if (! $artwork) {
            return;
        }

        try {
            $vectors->upsertArtwork($artwork);
        } catch (\Throwable $e) {
            Log::warning('SyncArtworkVectorIndexJob failed', [
                'artwork_id' => $this->artworkId,
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }
}
