<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Artwork;
use Illuminate\Bus\Queueable;
use Meilisearch\Client as MeilisearchClient;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * Queued job: remove a single artwork document from Meilisearch.
 */
class DeleteArtworkFromIndexJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries   = 3;
    public int $timeout = 30;

    public function __construct(public readonly int $artworkId) {}

    public function handle(MeilisearchClient $client): void
    {
        // Delete directly from the Meilisearch index — no Scout after_commit hop.
        $indexName = (new Artwork())->searchableAs();
        $client->index($indexName)->deleteDocument($this->artworkId);
    }

    public function failed(\Throwable $e): void
    {
        Log::error('DeleteArtworkFromIndexJob failed', [
            'artwork_id' => $this->artworkId,
            'error'      => $e->getMessage(),
        ]);
    }
}
