<?php

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('requires authentication to open setup username screen', function () {
    $this->get('/setup/username')
        ->assertRedirect('/login');
});

it('renders setup username screen for authenticated user', function () {
    $user = User::factory()->create([
        'onboarding_step' => 'password',
    ]);

    $this->actingAs($user)
        ->get('/setup/username')
        ->assertOk();
});

it('accepts unique username and completes onboarding', function () {
    $user = User::factory()->create([
        'username' => 'initial_user',
        'onboarding_step' => 'password',
    ]);

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

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

    $user->refresh();
    expect($user->username)->toBe('final_user_7');
    expect($user->onboarding_step)->toBe('complete');
    expect($user->username_changed_at)->not->toBeNull();
});

it('rejects reserved username in setup flow', function () {
    $user = User::factory()->create([
        'onboarding_step' => 'password',
    ]);

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

    expect($user->fresh()->onboarding_step)->toBe('password');
});

it('queues similarity-flagged username for manual approval in setup flow', function () {
    $user = User::factory()->create([
        'onboarding_step' => 'password',
    ]);

    $this->actingAs($user)
        ->from('/setup/username')
        ->post('/setup/username', [
            'username' => 'support1',
        ])
        ->assertRedirect('/setup/username')
        ->assertSessionHasErrors('username');

    $this->assertDatabaseHas('username_approval_requests', [
        'user_id' => $user->id,
        'requested_username' => 'support1',
        'context' => 'onboarding_username',
        'status' => 'pending',
    ]);
});
