<?php

namespace Tests\Feature;

use App\Filament\Resources\EventResource\Pages\ManageWatermark;
use App\Filament\SuperAdmin\Pages\GuestPolicySettingsPage;
use App\Filament\SuperAdmin\Pages\WatermarkSettingsPage;
use App\Models\Event;
use App\Models\SuperAdminActionLog;
use App\Models\User;
use App\Models\WatermarkSetting;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Tests\TestCase;

class SuperAdminAuditLogSettingsTest extends TestCase
{
    use RefreshDatabase;

    public function test_superadmin_settings_save_creates_audit_log(): void
    {
        $user = User::factory()->create(['role' => 'super_admin']);

        $this->bootSuperAdminPanel($user);

        Livewire::test(GuestPolicySettingsPage::class)
            ->set('guest_downloads_enabled', false)
            ->call('save');

        $this->assertTrue(SuperAdminActionLog::query()
            ->where('action', 'guest_policy.updated')
            ->exists());
    }

    public function test_event_watermark_save_creates_audit_log(): void
    {
        $user = User::factory()->create(['role' => 'super_admin']);
        $event = Event::factory()->create();

        $this->bootSuperAdminPanel($user);

        Livewire::test(ManageWatermark::class, ['record' => $event->getKey()])
            ->set('watermark_mode', 'base')
            ->set('watermark_position', 'top-left')
            ->call('save');

        $this->assertTrue(SuperAdminActionLog::query()
            ->where('action', 'event.watermark_updated')
            ->where('subject_id', $event->id)
            ->exists());
    }

    public function test_base_watermark_settings_save_creates_audit_log(): void
    {
        Storage::fake('public');

        $user = User::factory()->create(['role' => 'super_admin']);

        $this->bootSuperAdminPanel($user);

        $file = UploadedFile::fake()->image('watermark.png', 120, 120);

        Livewire::test(WatermarkSettingsPage::class)
            ->set('asset', [$file])
            ->call('save');

        $settings = WatermarkSetting::query()->first();

        $this->assertNotNull($settings);
        $this->assertNotNull($settings->asset);
        Storage::disk('public')->assertExists($settings->asset);

    }

    private function bootSuperAdminPanel(User $user): void
    {
        $panel = Filament::getPanel('superadmin');

        $this->assertNotNull($panel);

        Filament::setCurrentPanel($panel);
        Filament::bootCurrentPanel();
        Filament::auth()->login($user);
    }
}
