<?php

namespace Tests\Feature\Api\Tenant;

use App\Jobs\ProcessPhotoSecurityScan;
use App\Models\Event;
use App\Models\EventMediaAsset;
use App\Models\EventPackage;
use App\Models\MediaStorageTarget;
use App\Models\Package;
use App\Models\Photo;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Storage;
use Tests\Feature\Tenant\TenantTestCase;

class TenantPhotoUploadTest extends TenantTestCase
{
    public function test_tenant_can_upload_photo_and_store_media_assets(): void
    {
        config(['filesystems.default' => 'public']);
        Storage::fake('public');

        MediaStorageTarget::create([
            'key' => 'public',
            'name' => 'Public (test)',
            'driver' => 'local',
            'config' => [
                'root' => Storage::disk('public')->path(''),
                'url' => 'http://localhost/storage',
                'visibility' => 'public',
            ],
            'is_hot' => true,
            'is_default' => true,
            'is_active' => true,
            'priority' => 10,
        ]);

        $package = Package::factory()->endcustomer()->create([
            'max_photos' => 100,
            'gallery_days' => 14,
        ]);

        $event = Event::factory()->create([
            'tenant_id' => $this->tenant->id,
            'photo_upload_enabled' => true,
        ]);

        EventPackage::create([
            'event_id' => $event->id,
            'package_id' => $package->id,
            'purchased_price' => $package->price,
            'purchased_at' => now(),
            'used_photos' => 0,
            'gallery_expires_at' => now()->addDays(14),
        ]);

        Bus::fake();

        $response = $this->withHeaders([
            'Authorization' => 'Bearer '.$this->token,
        ])->postJson("/api/v1/tenant/events/{$event->slug}/photos", [
            'photo' => UploadedFile::fake()->image('photo.jpg', 800, 600),
        ]);

        $response->assertCreated()
            ->assertJsonPath('data.status', 'approved');

        $photo = Photo::query()->first();
        $this->assertNotNull($photo);
        Storage::disk('public')->assertExists($photo->file_path);

        $this->assertDatabaseHas(EventMediaAsset::class, [
            'photo_id' => $photo->id,
            'variant' => 'original',
            'disk' => 'public',
        ]);

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