<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Artwork;
use App\Services\Images\FeaturedArtworkThumbnailGenerator;
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 GenerateFeaturedArtworkThumbnailsJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $tries = 3;

    public int $timeout = 120;

    public function __construct(
        private readonly int $artworkId,
        private readonly bool $force = false,
    ) {
        $queue = (string) config('uploads.featured_thumbnails.queue', 'default');

        if ($queue !== '') {
            $this->onQueue($queue);
        }
    }

    public function handle(
        FeaturedArtworkThumbnailGenerator $generator,
    ): void {
        $artwork = Artwork::withTrashed()->find($this->artworkId);

        if (! $artwork instanceof Artwork) {
            return;
        }

        $result = $generator->generate($artwork, $this->force);

        if (($result['failed'] ?? []) !== []) {
            Log::warning('Featured artwork thumbnail generation had partial failures', [
                'artwork_id' => $artwork->id,
                'failed_variants' => array_keys((array) $result['failed']),
            ]);
        }
    }
}
