<?php

declare(strict_types=1);

use Builder\Core\Tests\BuilderTestUser;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Inertia\Testing\AssertableInertia;

beforeEach(function (): void {
    Schema::create('users', function ($table): void {
        $table->id();
        $table->string('name')->nullable();
        $table->string('email')->nullable();
        $table->string('password')->nullable();
        $table->timestamps();
    });
});

it('renders the login page for unauthenticated users', function (): void {
    $this->get(route('builder.login'))
        ->assertInertia(fn (AssertableInertia $page): AssertableInertia => $page->component('Auth/Login'));
});

it('redirects authenticated users from the login page to the dashboard', function (): void {
    $user = BuilderTestUser::create(['name' => 'Admin', 'email' => 'admin@test.com', 'password' => 'x']);

    $this->actingAs($user)
        ->get(route('builder.login'))
        ->assertRedirect(route('builder.dashboard'));
});

it('returns validation errors for invalid credentials', function (): void {
    BuilderTestUser::create([
        'name' => 'Admin',
        'email' => 'admin@test.com',
        'password' => Hash::make('correct-password'),
    ]);

    $this->post(route('builder.login.store'), [
        'email' => 'admin@test.com',
        'password' => 'wrong-password',
    ])->assertSessionHasErrors('email');
});

it('redirects to dashboard on valid credentials', function (): void {
    BuilderTestUser::create([
        'name' => 'Admin',
        'email' => 'admin@test.com',
        'password' => Hash::make('secret'),
    ]);

    $this->post(route('builder.login.store'), [
        'email' => 'admin@test.com',
        'password' => 'secret',
    ])->assertRedirect(route('builder.dashboard'));
});

it('logs out and redirects to login', function (): void {
    $user = BuilderTestUser::create(['name' => 'Admin', 'email' => 'admin@test.com', 'password' => 'x']);

    $this->actingAs($user)
        ->post(route('builder.logout'))
        ->assertRedirect(route('builder.login'));
});
