<?php

use App\Models\User;
use App\Uploads\Jobs\PreviewGenerationJob;
use App\Uploads\Jobs\VirusScanJob;
use App\Services\Uploads\UploadScanService;
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('dispatches PreviewGenerationJob when VirusScanJob marks upload clean', 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' => 'image',
        'status' => 'draft',
        'is_scanned' => false,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $mainPath = "tmp/drafts/{$uploadId}/main/main.jpg";
    Storage::disk('local')->put($mainPath, 'fake-image-content');

    DB::table('upload_files')->insert([
        'upload_id' => $uploadId,
        'path' => $mainPath,
        'type' => 'main',
        'hash' => null,
        'size' => 18,
        'mime' => 'image/jpeg',
        'created_at' => now(),
    ]);

    $job = new VirusScanJob($uploadId);
    $job->handle(app(UploadScanService::class));

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

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

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