<?php

namespace Tests\Feature;

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

class AuthTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }

    public function test_login_page_can_be_rendered(): void
    {
        $response = $this->get('/login');
        $response->assertStatus(200);
    }

    public function test_default_admin_can_login_and_redirects_to_force_change_password(): void
    {
        Livewire::test(Login::class)
            ->set('email', 'admin@smkn1gunungagung.sch.id')
            ->set('password', 'password123')
            ->call('login')
            ->assertRedirect(route('force-change-password'));

        $this->assertAuthenticated();
    }

    public function test_user_with_force_password_change_cannot_access_dashboard(): void
    {
        $user = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $this->actingAs($user);

        $response = $this->get('/dashboard');
        $response->assertRedirect(route('force-change-password'));
    }

    public function test_user_can_change_password_and_access_dashboard(): void
    {
        $user = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $this->actingAs($user);

        Livewire::test(ForceChangePassword::class)
            ->set('current_password', 'password123')
            ->set('new_password', 'AdminBaru#2026')
            ->set('new_password_confirmation', 'AdminBaru#2026')
            ->call('changePassword')
            ->assertRedirect(route('dashboard'));

        $this->assertFalse($user->fresh()->force_password_change);

        $response = $this->get('/dashboard');
        $response->assertStatus(200);
    }
}
