<?php

namespace Tests\Feature;

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

class OptionalOnboardingTest extends TestCase
{
    use RefreshDatabase;

    public function test_rotated_user_without_2fa_reaches_the_dashboard(): void
    {
        $user = User::factory()->create(['must_change_password' => false]);

        $this->actingAs($user)->get('/')->assertOk();
    }

    public function test_user_that_must_change_password_is_still_redirected(): void
    {
        $user = User::factory()->create(['must_change_password' => true]);

        $this->actingAs($user)->get('/')->assertRedirect(route('password.change'));
    }

    public function test_password_change_lands_on_dashboard_not_2fa_setup(): void
    {
        $user = User::factory()->create(['must_change_password' => true, 'password' => bcrypt('old-Password-1')]);

        Livewire::actingAs($user)->test(PasswordChange::class)
            ->set('current', 'old-Password-1')
            ->set('password', 'new-Password-123')
            ->set('password_confirmation', 'new-Password-123')
            ->call('update')
            ->assertRedirect(route('dashboard'));
    }

    public function test_broadcast_gate_passes_on_password_rotation_alone(): void
    {
        $user = User::factory()->create(['must_change_password' => false]);

        $this->assertTrue($user->securityOnboarded());
    }

    public function test_password_change_can_be_skipped_without_rotating(): void
    {
        $user = User::factory()->create(['must_change_password' => true]);

        Livewire::actingAs($user)->test(PasswordChange::class)
            ->call('skip')
            ->assertRedirect(route('dashboard'));

        // Skipping does NOT rotate — the flag (and the warning banner) stay until a real change.
        $this->assertTrue($user->fresh()->must_change_password);
        $this->assertTrue(session('onboarding.password_skipped'));
    }

    public function test_a_skipped_session_is_no_longer_redirected(): void
    {
        $user = User::factory()->create(['must_change_password' => true]);

        $this->actingAs($user)
            ->withSession(['onboarding.password_skipped' => true])
            ->get('/')
            ->assertOk();
    }
}
