<?php

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;

uses(RefreshDatabase::class);

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

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

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

it('accepts strong password and moves onboarding to password step', function () {
    $user = User::factory()->create([
        'onboarding_step' => 'verified',
        'needs_password_reset' => true,
        'password' => Hash::make('old-password'),
    ]);

    $response = $this->actingAs($user)
        ->post('/setup/password', [
            'password' => 'StrongPass1!',
            'password_confirmation' => 'StrongPass1!',
        ]);

    $response->assertRedirect('/setup/username');

    $user->refresh();
    expect(Hash::check('StrongPass1!', $user->password))->toBeTrue();
    expect($user->onboarding_step)->toBe('password');
    expect((bool) $user->needs_password_reset)->toBeFalse();
});

it('rejects password without number or symbol or minimum length', function () {
    $user = User::factory()->create([
        'onboarding_step' => 'verified',
        'needs_password_reset' => true,
    ]);

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

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