<?php

use App\Models\User;
use App\Uploads\Jobs\PreviewGenerationJob;
use App\Uploads\Jobs\TagAnalysisJob;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

uses(RefreshDatabase::class);

it('PreviewGenerationJob dispatches TagAnalysisJob', function () {
    Storage::fake('local');
    Bus::fake();

    $user = User::factory()->create();
    $uploadId = (string) Str::uuid();

    DB::table('uploads')->insert([
        'id' => $uploadId,
        'user_id' => $user->id,
        'type' => 'archive',
        'status' => 'draft',
        'is_scanned' => true,
        'has_tags' => false,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    // archive path with no screenshot uses placeholder path in PreviewService
    $job = new PreviewGenerationJob($uploadId);
    $job->handle(app(\App\Services\Upload\PreviewService::class));

    $this->assertDatabaseHas('uploads', [
        'id' => $uploadId,
    ]);

    Bus::assertDispatched(TagAnalysisJob::class, function (TagAnalysisJob $queuedJob) use ($uploadId) {
        $reflect = new ReflectionClass($queuedJob);
        $property = $reflect->getProperty('uploadId');
        $property->setAccessible(true);

        return $property->getValue($queuedJob) === $uploadId;
    });
});
