<?php

namespace Tests\Feature;

use App\Console\Commands\SeedDemoSwitcherTenants;
use App\Models\Event;
use App\Models\MediaStorageTarget;
use App\Models\Photo;
use Illuminate\Console\OutputStyle;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Tests\TestCase;

class SeedDemoSwitcherTenantsTest extends TestCase
{
    use RefreshDatabase;

    public function test_demo_seeder_records_media_assets_on_event_disk(): void
    {
        Storage::fake('local-ssd');

        MediaStorageTarget::create([
            'key' => 'local-ssd',
            'name' => 'Local SSD',
            'driver' => 'local',
            'config' => [],
            'is_hot' => true,
            'is_default' => true,
            'is_active' => true,
            'priority' => 10,
        ]);

        $event = Event::factory()->create();

        $originalUrl = 'https://images.test/demo-original.jpg';
        $thumbUrl = 'https://images.test/demo-thumb.jpg';

        Http::fake([
            $originalUrl => Http::response('demo-original', 200, ['Content-Type' => 'image/jpeg']),
            $thumbUrl => Http::response('demo-thumb', 200, ['Content-Type' => 'image/jpeg']),
        ]);

        $command = app(SeedDemoSwitcherTenants::class);
        $command->setOutput(new OutputStyle(new ArrayInput([]), new NullOutput));
        $method = new \ReflectionMethod($command, 'storePhotos');
        $method->setAccessible(true);

        $method->invoke($command, $event, [
            [
                'src' => [
                    'large2x' => $originalUrl,
                    'medium' => $thumbUrl,
                ],
            ],
        ], 1);

        $photo = Photo::where('event_id', $event->id)->first();

        $this->assertNotNull($photo);
        $this->assertNotNull($photo->media_asset_id);
        $this->assertSame('approved', $photo->status);

        Storage::disk('local-ssd')->assertExists($photo->file_path);
        Storage::disk('local-ssd')->assertExists($photo->thumbnail_path);

        $this->assertDatabaseHas('event_media_assets', [
            'photo_id' => $photo->id,
            'variant' => 'original',
            'disk' => 'local-ssd',
            'path' => $photo->file_path,
        ]);

        $this->assertDatabaseHas('event_media_assets', [
            'photo_id' => $photo->id,
            'variant' => 'thumbnail',
            'disk' => 'local-ssd',
            'path' => $photo->thumbnail_path,
        ]);
    }
}
