<?php

namespace Tests\Feature;

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

class AdminSecurityTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Test guest cannot access admin dashboard.
     */
    public function test_guest_is_redirected_to_admin_login(): void
    {
        $response = $this->get(route('admin.dashboard'));

        $response->assertRedirect(route('admin.login'));
    }

    /**
     * Test admin user can access admin dashboard.
     */
    public function test_admin_user_can_access_admin_dashboard(): void
    {
        $admin = User::factory()->create([
            'role' => 'admin',
        ]);

        $response = $this->actingAs($admin)->get(route('admin.dashboard'));

        $response->assertStatus(200);
    }

    /**
     * Test non-admin user is redirected and logged out when trying to access admin dashboard.
     */
    public function test_non_admin_user_cannot_access_admin_dashboard(): void
    {
        $user = User::factory()->create([
            'role' => 'user',
        ]);

        $response = $this->actingAs($user)->get(route('admin.dashboard'));

        $response->assertRedirect(route('admin.login'));
        $response->assertSessionHasErrors(['email']);
        $this->assertGuest();
    }

    /**
     * Test admin can login through auth form.
     */
    public function test_admin_can_login_via_auth_form(): void
    {
        $admin = User::factory()->create([
            'email' => 'admin@silapor.id',
            'password' => Hash::make('password'),
            'role' => 'admin',
        ]);

        $response = $this->post(route('admin.login.store'), [
            'email' => 'admin@silapor.id',
            'password' => 'password',
        ]);

        $response->assertRedirect(route('admin.dashboard'));
        $this->assertAuthenticatedAs($admin);
    }

    /**
     * Test non-admin login attempt fails on the form.
     */
    public function test_non_admin_login_fails_via_auth_form(): void
    {
        $user = User::factory()->create([
            'email' => 'user@silapor.id',
            'password' => Hash::make('password'),
            'role' => 'user',
        ]);

        $response = $this->post(route('admin.login.store'), [
            'email' => 'user@silapor.id',
            'password' => 'password',
        ]);

        $response->assertRedirect();
        $response->assertSessionHasErrors(['email']);
        $this->assertGuest();
    }
}
