<?php

declare(strict_types=1);

namespace App\Uploads\Jobs;

use App\Services\Upload\PreviewService;
use App\Uploads\Jobs\TagAnalysisJob;
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\DB;
use Illuminate\Support\Facades\Storage;

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

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

    public function __construct(private readonly string $uploadId)
    {
    }

    public function handle(PreviewService $previewService): void
    {
        $upload = DB::table('uploads')->where('id', $this->uploadId)->first();
        if (! $upload) {
            return;
        }

        if ((string) $upload->status !== 'draft' || ! (bool) $upload->is_scanned) {
            return;
        }

        $this->advanceProcessingState('generating_preview', ['pending_scan', 'scanning', 'generating_preview']);

        $previewData = null;

        if ((string) $upload->type === 'image') {
            $main = DB::table('upload_files')
                ->where('upload_id', $this->uploadId)
                ->where('type', 'main')
                ->orderBy('id')
                ->first(['path']);

            if (! $main || ! Storage::disk('local')->exists((string) $main->path)) {
                return;
            }

            $previewData = $previewService->generateFromImage($this->uploadId, (string) $main->path);
        } elseif ((string) $upload->type === 'archive') {
            $screenshot = DB::table('upload_files')
                ->where('upload_id', $this->uploadId)
                ->where('type', 'screenshot')
                ->orderBy('id')
                ->first(['path']);

            $previewData = $previewService->generateFromArchive($this->uploadId, $screenshot?->path ? (string) $screenshot->path : null);
        } else {
            return;
        }

        $previewPath = (string) ($previewData['preview_path'] ?? '');
        if ($previewPath === '') {
            return;
        }

        DB::table('uploads')->where('id', $this->uploadId)->update([
            'preview_path' => $previewPath,
            'updated_at' => now(),
        ]);

        $this->advanceProcessingState('analyzing_tags', ['pending_scan', 'scanning', 'generating_preview', 'analyzing_tags']);

        DB::table('upload_files')
            ->where('upload_id', $this->uploadId)
            ->where('type', 'preview')
            ->delete();

        DB::table('upload_files')->insert([
            'upload_id' => $this->uploadId,
            'path' => $previewPath,
            'type' => 'preview',
            'hash' => null,
            'size' => Storage::disk('local')->exists($previewPath) ? Storage::disk('local')->size($previewPath) : null,
            'mime' => 'image/webp',
            'created_at' => now(),
        ]);

        TagAnalysisJob::dispatch($this->uploadId);
    }

    /**
     * @param array<int, string> $allowedCurrentStates
     */
    private function advanceProcessingState(string $targetState, array $allowedCurrentStates): void
    {
        DB::table('uploads')
            ->where('id', $this->uploadId)
            ->where('status', 'draft')
            ->where(function ($query) use ($allowedCurrentStates): void {
                $query->whereNull('processing_state')
                    ->orWhereIn('processing_state', $allowedCurrentStates);
            })
            ->update([
                'processing_state' => $targetState,
                'updated_at' => now(),
            ]);
    }
}
