<?php

use App\Models\User;

test('registration normalizes username to lowercase', function () {
    $user = User::factory()->create([
        'onboarding_step' => 'password',
        'username' => null,
    ]);

    $response = $this->actingAs($user)->post('/setup/username', [
        'username' => '  GregOr_One  ',
    ]);

    $response->assertRedirect('/@gregor_one');

    $this->assertDatabaseHas('users', [
        'id' => $user->id,
        'username' => 'gregor_one',
    ]);
});

test('registration rejects reserved usernames', function () {
    $user = User::factory()->create([
        'onboarding_step' => 'password',
    ]);

    $response = $this->actingAs($user)->from('/setup/username')->post('/setup/username', [
        'username' => 'admin',
    ]);

    $response->assertSessionHasErrors('username');
    $this->assertAuthenticatedAs($user);
});

test('legacy profile username route redirects to canonical at-username route', function () {
    $user = User::factory()->create(['username' => 'author_two']);

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

    $response->assertRedirect('/@author_two');
});

test('non-canonical at-username route redirects to lowercase canonical route', function () {
    $user = User::factory()->create(['username' => 'author_two']);

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

    $response->assertRedirect('/@author_two');
});

test('profile username update writes history and redirect map', function () {
    $user = User::factory()->create([
        'username' => 'oldname',
        'username_changed_at' => now()->subDays(120),
    ]);

    $response = $this
        ->actingAs($user)
        ->patch('/profile', [
            'username' => 'New_Name',
            'name' => $user->name,
            'email' => $user->email,
        ]);

    $response->assertRedirect('/dashboard/profile');

    $this->assertDatabaseHas('users', [
        'id' => $user->id,
        'username' => 'new_name',
    ]);

    $this->assertDatabaseHas('username_history', [
        'user_id' => $user->id,
        'old_username' => 'oldname',
    ]);

    $this->assertDatabaseHas('username_redirects', [
        'old_username' => 'oldname',
        'new_username' => 'new_name',
        'user_id' => $user->id,
    ]);
});
