<?php

namespace Tests\Feature\Photobooth;

use App\Jobs\ProcessPhotoSecurityScan;
use App\Models\Emotion;
use App\Models\Event;
use App\Models\EventPackage;
use App\Models\EventPhotoboothSetting;
use App\Models\MediaStorageTarget;
use App\Models\Package;
use App\Models\Photo;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

class PhotoboothIngestCommandTest extends TestCase
{
    use RefreshDatabase;

    #[Test]
    public function it_ingests_pending_files_and_marks_them_as_photobooth(): void
    {
        Storage::fake('photobooth');
        Storage::fake('public');

        config([
            'photobooth.import.disk' => 'photobooth',
            'photobooth.import.max_files' => 10,
            'filesystems.default' => 'public',
        ]);

        MediaStorageTarget::create([
            'key' => 'public',
            'name' => 'Local Public',
            'driver' => 'local',
            'config' => [
                'root' => storage_path('app/public'),
                'url' => env('APP_URL').'/storage',
                'visibility' => 'public',
            ],
            'is_hot' => true,
            'is_default' => true,
            'is_active' => true,
            'priority' => 1,
        ]);

        $tenant = Tenant::factory()->create();
        $event = Event::factory()
            ->for($tenant)
            ->create([
                'slug' => 'demo-event',
                'status' => 'published',
            ]);

        $setting = EventPhotoboothSetting::factory()
            ->for($event)
            ->create([
                'enabled' => true,
                'mode' => 'ftp',
                'path' => $tenant->slug.'/'.$event->id,
            ]);

        $package = Package::factory()->create(['max_photos' => 5]);
        EventPackage::create([
            'event_id' => $event->id,
            'package_id' => $package->id,
            'purchased_price' => 0,
            'used_photos' => 0,
        ]);

        Storage::disk('photobooth')->makeDirectory($setting->path);
        Storage::disk('photobooth')->put($setting->path.'/sample.jpg', $this->sampleImage());
        Emotion::factory()->create();

        Bus::fake();

        $this->artisan('photobooth:ingest', ['--event' => $event->id])
            ->assertExitCode(0);

        $this->assertDatabaseHas('photos', [
            'event_id' => $event->id,
            'ingest_source' => Photo::SOURCE_PHOTOBOOTH,
        ]);

        Storage::disk('photobooth')->assertMissing($setting->path.'/sample.jpg');

        Bus::assertDispatched(ProcessPhotoSecurityScan::class);
    }

    private function sampleImage(): string
    {
        return base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==');
    }
}
