<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Artwork;
use App\Jobs\GenerateArtworkEmbeddingJob;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public int $tries = 1;

    public int $timeout = 120;

    public function __construct(
        private readonly int $afterId = 0,
        private readonly int $batchSize = 200,
        private readonly bool $force = false,
    ) {
        $queue = (string) config('recommendations.queue', config('vision.queue', 'default'));
        if ($queue !== '') {
            $this->onQueue($queue);
        }
    }

    public function handle(): void
    {
        $batch = max(1, min($this->batchSize, 1000));

        $artworks = Artwork::query()
            ->where('id', '>', $this->afterId)
            ->whereNotNull('hash')
            ->orderBy('id')
            ->limit($batch)
            ->get(['id', 'hash']);

        if ($artworks->isEmpty()) {
            return;
        }

        foreach ($artworks as $artwork) {
            GenerateArtworkEmbeddingJob::dispatch((int) $artwork->id, (string) $artwork->hash, $this->force);
        }

        if ($artworks->count() === $batch) {
            $lastId = (int) $artworks->last()->id;
            self::dispatch($lastId, $batch, $this->force);
        }
    }
}
