<?php

namespace Tests\Feature;

use App\Filament\Resources\EventResource\Pages\ManageWatermark;
use App\Filament\SuperAdmin\Pages\GuestPolicySettingsPage;
use App\Models\Event;
use App\Models\SuperAdminActionLog;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
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());
    }

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

        $this->assertNotNull($panel);

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