<?php

namespace Tests\Feature;

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

class AuthenticationTest extends TestCase
{
    use RefreshDatabase;

    public function test_login_page_uses_the_updated_erp_interface(): void
    {
        $this->get('/login')
            ->assertOk()
            ->assertSee('Welcome back')
            ->assertSee('Sales &amp; invoicing', false)
            ->assertSee('Live inventory')
            ->assertSee('Sign in securely')
            ->assertSee('name="login"', false)
            ->assertSee('name="password"', false);
    }

    public function test_seeded_administrator_can_log_in_and_out_with_audit_history(): void
    {
        $this->withoutMiddleware(ValidateCsrfToken::class);
        $this->seed();

        $user = User::where('username', 'admin')->firstOrFail();

        $this->post('/login', [
            'login' => 'admin',
            'password' => 'Password123!',
        ])->assertRedirect(route('dashboard'));

        $this->assertAuthenticatedAs($user);
        $this->assertDatabaseHas('login_logs', [
            'user_id' => $user->id,
            'status' => 'success',
        ]);
        $this->assertDatabaseHas('audit_logs', [
            'user_id' => $user->id,
            'action' => 'USER_LOGIN',
            'module' => 'Auth',
        ]);

        $this->post('/logout')->assertRedirect(route('login'));

        $this->assertGuest();
        $this->assertDatabaseHas('audit_logs', [
            'user_id' => $user->id,
            'action' => 'USER_LOGOUT',
            'module' => 'Auth',
        ]);
    }
}
