<?php

use App\Models\User;

test('login screen can be rendered', function () {
    $response = $this->get('/login');

    $response->assertStatus(200)
        ->assertSee('Read signup and login help')
        ->assertSee(route('help.auth'), false)
        ->assertSee(route('help.troubleshooting'), false);
});

test('users can authenticate using the login screen', function () {
    $user = User::factory()->create();

    $response = $this->post('/login', [
        'email' => $user->email,
        'password' => 'password',
    ]);

    $this->assertAuthenticated();
    $response->assertRedirect(route('dashboard', absolute: false));
});

test('users with incomplete onboarding can authenticate with username', function () {
    $user = User::factory()->create([
        'onboarding_step' => null,
    ]);

    $response = $this->post('/login', [
        'email' => $user->username,
        'password' => 'password',
    ]);

    $this->assertAuthenticatedAs($user);
    $response->assertRedirect(route('setup.email.create', absolute: false));
});

test('legacy users pending email upgrade can authenticate with username', function () {
    $user = User::factory()->create([
        'email' => 'legacy-user@users.skinbase.org',
        'onboarding_step' => null,
    ]);

    $response = $this->post('/login', [
        'email' => $user->username,
        'password' => 'password',
    ]);

    $this->assertAuthenticatedAs($user);
    $response->assertRedirect(route('setup.email.create', absolute: false));
});

test('standard users can not authenticate with username', function () {
    config()->set('app.debug', false);

    $user = User::factory()->create();

    $response = $this->from('/login')->post('/login', [
        'email' => $user->username,
        'password' => 'password',
    ]);

    $this->assertGuest();
    $response->assertRedirect('/login');
    $response->assertSessionHasErrors('email');
});

test('username-login upgrade session redirects users to setup email flow', function () {
    $user = User::factory()->create([
        'email' => 'legacy-user@users.skinbase.org',
        'onboarding_step' => null,
    ]);

    $response = $this->actingAs($user)
        ->withSession(['username_login_upgrade' => true])
        ->get('/dashboard');

    $response->assertRedirect(route('setup.email.create', absolute: false));
});

test('users can not authenticate with invalid password', function () {
    config()->set('app.debug', false);

    $user = User::factory()->create();

    $response = $this->from('/login')->post('/login', [
        'email' => $user->email,
        'password' => 'wrong-password',
    ]);

    $this->assertGuest();
    $response->assertRedirect('/login');
    $response->assertSessionHasErrors('email');
});

test('users can logout', function () {
    $user = User::factory()->create();

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

    $this->assertGuest();
    $response->assertRedirect('/');
});
