<?php

namespace Tests\Feature;

use App\Http\Middleware\UiMode;
use App\Models\User;
use App\Models\UserPreference;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UiModeTest extends TestCase
{
    use RefreshDatabase;

    public function test_items_index_defaults_to_classic_view(): void
    {
        $response = $this->get('/items');

        $response->assertOk();
        $response->assertDontSee('Gear for sale');
    }

    public function test_ui_query_param_switches_to_simple_view_and_sets_cookie(): void
    {
        $response = $this->get('/items?ui=simple');

        $response->assertOk();
        $response->assertSee('Gear for sale');
        $response->assertCookie(UiMode::COOKIE, 'simple');
    }

    public function test_cookie_persists_simple_view_for_guests(): void
    {
        $response = $this->withCookie(UiMode::COOKIE, 'simple')->get('/items');

        $response->assertOk();
        $response->assertSee('Gear for sale');
    }

    public function test_invalid_ui_values_fall_back_to_classic(): void
    {
        $this->get('/items?ui=bogus')->assertOk()->assertDontSee('Gear for sale');
        $this->withCookie(UiMode::COOKIE, 'bogus')->get('/items')->assertOk()->assertDontSee('Gear for sale');
    }

    public function test_explicit_choice_is_saved_to_user_preferences(): void
    {
        $user = User::factory()->create();

        $this->actingAs($user)->get('/items?ui=simple')->assertOk();

        $this->assertSame('simple', $user->preferences()->first()->ui_mode);
    }

    public function test_saved_preference_wins_over_cookie(): void
    {
        $user = User::factory()->create();
        UserPreference::create(['user_id' => $user->id, 'ui_mode' => 'simple']);

        $response = $this->actingAs($user)
            ->withCookie(UiMode::COOKIE, 'classic')
            ->get('/items');

        $response->assertOk();
        $response->assertSee('Gear for sale');
    }

    public function test_switching_back_to_classic_updates_saved_preference(): void
    {
        $user = User::factory()->create();
        UserPreference::create(['user_id' => $user->id, 'ui_mode' => 'simple']);

        $this->actingAs($user)->get('/items?ui=classic')->assertOk()->assertDontSee('Gear for sale');

        $this->assertSame('classic', $user->preferences()->first()->ui_mode);
    }
}
