<?php

namespace Tests\Feature\Admin;

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

class AdminSettingsControllerTest extends TestCase
{
    use RefreshDatabase;

    private User $admin;

    protected function setUp(): void
    {
        parent::setUp();

        $this->admin = User::factory()->create([
            'is_admin' => true,
            'admin_approved_at' => now(),
        ]);

        $this->actingAs($this->admin);
    }

    public function test_admin_can_view_settings_page(): void
    {
        $response = $this->get(route('admin.settings.index'));

        $response->assertStatus(200);
        $response->assertViewIs('admin.settings.index');
        $response->assertViewHas('settings');
    }

    public function test_admin_can_update_settings(): void
    {
        $settingsData = [
            'app_name' => 'Test App',
            'app_url' => 'https://test.com',
            'default_currency' => 'USD',
            'import_batch_size' => 25,
        ];

        $response = $this->put(route('admin.settings.update'), $settingsData);

        $response->assertRedirect(route('admin.settings.index'));
        $response->assertSessionHas('success');
    }

    public function test_admin_cannot_update_settings_with_invalid_data(): void
    {
        $response = $this->put(route('admin.settings.update'), [
            'app_name' => '',
            'app_url' => 'not-a-valid-url',
            'default_currency' => 'invalid',
            'import_batch_size' => 'not-a-number',
        ]);

        $response->assertSessionHasErrors(['app_name', 'app_url', 'default_currency', 'import_batch_size']);
    }

    public function test_admin_cannot_update_settings_with_invalid_currency(): void
    {
        $response = $this->put(route('admin.settings.update'), [
            'app_name' => 'Test App',
            'app_url' => 'https://test.com',
            'default_currency' => 'GBP',
            'import_batch_size' => 50,
        ]);

        $response->assertSessionHasErrors(['default_currency']);
    }

    public function test_admin_cannot_update_settings_with_batch_size_out_of_range(): void
    {
        $response = $this->put(route('admin.settings.update'), [
            'app_name' => 'Test App',
            'app_url' => 'https://test.com',
            'default_currency' => 'EGP',
            'import_batch_size' => 150,
        ]);

        $response->assertSessionHasErrors(['import_batch_size']);
    }

    public function test_settings_page_displays_system_information(): void
    {
        $response = $this->get(route('admin.settings.index'));

        $response->assertStatus(200);
        $response->assertSee('PHP Version');
        $response->assertSee('Laravel Version');
        $response->assertSee('Environment');
    }
}
