<?php

namespace Tests\Feature\Auth;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Livewire\Volt\Volt;
use Tests\TestCase;

class AuthenticationTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        config(['portal.id' => 1]);

        Schema::connection('admin')->create('portal_users', function ($table) {
            $table->integer('user_id')->primary();
            $table->string('username');
            $table->string('first_name')->nullable();
            $table->string('last_name')->nullable();
            $table->string('email')->nullable();
            $table->string('password');
            $table->unsignedTinyInteger('status')->default(1);
            $table->unsignedTinyInteger('is_superuser')->default(0);
        });

        Schema::connection('admin')->create('portal_pages', function ($table) {
            $table->integer('page_id')->primary();
            $table->integer('portal_id');
            $table->string('page_url');
            $table->unsignedTinyInteger('status')->default(1);
        });

        Schema::connection('admin')->create('portal_users_permissions', function ($table) {
            $table->integer('user_id');
            $table->integer('page_id');
            $table->unsignedTinyInteger('status')->default(1);
        });

        DB::connection('admin')->table('portal_pages')->insert([
            'page_id' => 7,
            'portal_id' => 1,
            'page_url' => 'mngt.home',
            'status' => 1,
        ]);
    }

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

        $response
            ->assertOk()
            ->assertSeeVolt('pages.auth.login')
            ->assertSee('Welcome back', false)
            ->assertSee('Username or email', false)
            ->assertDontSee('Get Started', false)
            ->assertDontSee('Laravel', false)
            ->assertDontSee('data-action="toggle-theme"', false);
    }

    public function test_users_can_authenticate_using_the_login_screen(): void
    {
        $this->portalUser();

        $component = Volt::test('pages.auth.login')
            ->set('form.identity', 'casey')
            ->set('form.password', 'secret-pass');

        $component->call('login');

        $component
            ->assertHasNoErrors()
            ->assertRedirect(route('home', absolute: false));

        $this->assertAuthenticated();
        $this->assertDatabaseHas('users', [
            'email' => 'casey@example.com',
            'name' => 'Casey Ng',
            'portal_user_id' => 41,
        ]);
    }

    public function test_users_can_authenticate_with_their_email(): void
    {
        $this->portalUser();

        Volt::test('pages.auth.login')
            ->set('form.identity', 'casey@example.com')
            ->set('form.password', 'secret-pass')
            ->call('login')
            ->assertHasNoErrors()
            ->assertRedirect(route('home', absolute: false));

        $this->assertAuthenticated();
    }

    public function test_users_can_not_authenticate_with_invalid_password(): void
    {
        $this->portalUser();

        $component = Volt::test('pages.auth.login')
            ->set('form.identity', 'casey')
            ->set('form.password', 'wrong-password');

        $component->call('login');

        $component
            ->assertHasErrors('form.identity')
            ->assertNoRedirect();

        $this->assertGuest();
    }

    public function test_users_without_portal_access_cannot_authenticate(): void
    {
        $this->portalUser(withPage: false);

        Volt::test('pages.auth.login')
            ->set('form.identity', 'casey')
            ->set('form.password', 'secret-pass')
            ->call('login')
            ->assertHasErrors('form.identity')
            ->assertNoRedirect();

        $this->assertGuest();
    }

    public function test_superusers_can_authenticate_without_a_page_grant(): void
    {
        $this->portalUser(['is_superuser' => 1], withPage: false);

        Volt::test('pages.auth.login')
            ->set('form.identity', 'casey')
            ->set('form.password', 'secret-pass')
            ->call('login')
            ->assertHasNoErrors()
            ->assertRedirect(route('home', absolute: false));

        $this->assertAuthenticated();
    }

    public function test_an_existing_local_user_is_linked_by_email(): void
    {
        $local = User::factory()->create([
            'email' => 'casey@example.com',
            'name' => 'Old Name',
        ]);
        $this->portalUser();

        Volt::test('pages.auth.login')
            ->set('form.identity', 'casey')
            ->set('form.password', 'secret-pass')
            ->call('login')
            ->assertHasNoErrors();

        $this->assertAuthenticatedAs($local);
        $this->assertSame(41, (int) $local->fresh()->portal_user_id);
        $this->assertSame(1, User::query()->count());
    }

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

        $this->actingAs($user);

        $response = $this->get('/home');

        $response
            ->assertOk()
            ->assertSee('data-action="toggle-theme"', false)
            ->assertSee('data-bs-theme', false)
            ->assertDontSee('Laravel', false);
    }

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

        $this->actingAs($user);

        $response = $this->post('/logout');

        $response->assertRedirect('/');

        $this->assertGuest();
    }

    /**
     * @param  array<string, mixed>  $overrides
     */
    private function portalUser(array $overrides = [], bool $withPage = true): void
    {
        DB::connection('admin')->table('portal_users')->insert(array_merge([
            'user_id' => 41,
            'username' => 'casey',
            'first_name' => 'Casey',
            'last_name' => 'Ng',
            'email' => 'casey@example.com',
            'password' => md5('secret-pass'),
            'status' => 1,
            'is_superuser' => 0,
        ], $overrides));

        if ($withPage) {
            DB::connection('admin')->table('portal_users_permissions')->insert([
                'user_id' => $overrides['user_id'] ?? 41,
                'page_id' => 7,
                'status' => 1,
            ]);
        }
    }
}
