<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ManageSettingsTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Guest users cannot access store settings.
     */
    public function test_guests_are_redirected_from_store_settings()
    {
        $response = $this->get('/admin/manage-settings');

        // Filament auth middleware will redirect to admin login
        $response->assertRedirect('/admin/login');
    }

    /**
     * Non-admin users (e.g. customers) cannot access store settings.
     */
    public function test_customers_cannot_access_store_settings()
    {
        $customer = User::factory()->create([
            'role' => 'customer',
        ]);

        $response = $this->actingAs($customer)->get('/admin/manage-settings');

        // Since they cannot access the panel, they get 403 or redirect
        $response->assertStatus(403);
    }

    /**
     * Admin users can access the store settings page successfully.
     */
    public function test_admins_can_access_store_settings()
    {
        $admin = User::factory()->create([
            'role' => 'admin',
        ]);

        $response = $this->actingAs($admin)->get('/admin/manage-settings');

        $response->assertStatus(200);
        $response->assertSee('Store Settings');
        $response->assertSee('General');
        $response->assertSee('Courier Logistics');
        $response->assertSee('Payment Gateways');
        $response->assertSee('SMS');
        $response->assertSee('Notifications');
        $response->assertSee('SMS Templates');
        $response->assertSee('Email (SMTP)');
        $response->assertSee('Branding');
        $response->assertSee('Clear Cache');
    }

    /**
     * Test that the Clear Cache header action actually clears the settings cache.
     */
    public function test_clear_cache_action_clears_settings_cache()
    {
        $admin = User::factory()->create([
            'role' => 'admin',
        ]);

        $this->actingAs($admin);
        \Livewire\Livewire::actingAs($admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        // Put something in the cache
        \Illuminate\Support\Facades\Cache::put('setting_some_key', 'cached_value');
        $this->assertTrue(\Illuminate\Support\Facades\Cache::has('setting_some_key'));

        // Call the page action
        \Livewire\Livewire::test(\App\Filament\Pages\ManageSettings::class)
            ->callAction('clearCache');

        // Verify the cache has been cleared
        $this->assertFalse(\Illuminate\Support\Facades\Cache::has('setting_some_key'));
    }
}
