<?php

declare(strict_types=1);

namespace App\Uploads\Jobs;

use App\Services\Upload\TagAnalysisService;
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;

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

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

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

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

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

        if (! (bool) $upload->is_scanned) {
            return;
        }

        if (empty($upload->preview_path)) {
            return;
        }

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

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

        $filename = $main ? basename((string) $main->path) : '';
        $categoryContext = null;

        if (! empty($upload->category_id)) {
            $category = DB::table('categories')->where('id', (int) $upload->category_id)->first(['name', 'slug']);
            if ($category) {
                $categoryContext = (string) ($category->name ?: $category->slug);
            }
        }

        $tags = $analysis->analyze($filename, (string) $upload->preview_path, $categoryContext);

        DB::transaction(function () use ($tags): void {
            DB::table('upload_tags')->where('upload_id', $this->uploadId)->delete();

            foreach ($tags as $row) {
                $tagName = (string) ($row['tag'] ?? '');
                if ($tagName === '') {
                    continue;
                }

                $slug = $tagName;
                $tag = DB::table('tags')->where('slug', $slug)->first(['id']);
                if (! $tag) {
                    $tagId = DB::table('tags')->insertGetId([
                        'name' => $tagName,
                        'slug' => $slug,
                        'usage_count' => 0,
                        'is_active' => true,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                } else {
                    $tagId = (int) $tag->id;
                }

                DB::table('upload_tags')->insert([
                    'upload_id' => $this->uploadId,
                    'tag_id' => $tagId,
                    'confidence' => (float) ($row['confidence'] ?? 0.0),
                    'source' => (string) ($row['source'] ?? 'manual'),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            DB::table('uploads')->where('id', $this->uploadId)->update([
                'has_tags' => true,
                'processing_state' => DB::raw("CASE WHEN processing_state IN ('ready','published','rejected') THEN processing_state ELSE 'ready' END"),
                'updated_at' => now(),
            ]);
        });
    }

    /**
     * @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(),
            ]);
    }
}
