<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Services\Uploads\UploadQueueService;
use App\Services\Uploads\UploadPipelineService;
use App\Jobs\AnalyzeArtworkAiAssistJob;
use App\Jobs\AutoTagArtworkJob;
use App\Jobs\DetectArtworkMaturityJob;
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 GenerateDerivativesJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(
        private readonly string $sessionId,
        private readonly string $hash,
        private readonly int $artworkId,
        private readonly ?string $originalFileName = null,
        private readonly ?string $archiveSessionId = null,
        private readonly ?string $archiveHash = null,
        private readonly ?string $archiveOriginalFileName = null,
        private readonly array $additionalScreenshotSessions = [],
        private readonly ?int $batchItemId = null,
    ) {
    }

    public function handle(UploadPipelineService $pipeline, UploadQueueService $queue): void
    {
        $pipeline->processAndPublish(
            $this->sessionId,
            $this->hash,
            $this->artworkId,
            $this->originalFileName,
            $this->archiveSessionId,
            $this->archiveHash,
            $this->archiveOriginalFileName,
            $this->additionalScreenshotSessions
        );

        if ($this->batchItemId) {
            $queue->markItemMediaProcessed($this->batchItemId);
        }

        // Auto-tagging is async and must never block publish.
        AutoTagArtworkJob::dispatch($this->artworkId, $this->hash)->afterCommit();
        DetectArtworkMaturityJob::dispatch($this->artworkId, $this->hash)->afterCommit();
        GenerateArtworkEmbeddingJob::dispatch($this->artworkId, $this->hash)->afterCommit();
        AnalyzeArtworkAiAssistJob::dispatch($this->artworkId)->afterCommit();
    }

    public function failed(\Throwable $exception): void
    {
        if (! $this->batchItemId) {
            return;
        }

        app(UploadQueueService::class)->markItemFailed(
            $this->batchItemId,
            'derivatives_failed',
            $exception->getMessage()
        );
    }
}
