<?php

namespace Tests\Feature;

use App\Models\Company;
use App\Models\User;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
use Tests\TestCase;

class WebPasswordResetTest extends TestCase
{
    use RefreshDatabase;

    public function test_forgot_password_page_is_accessible(): void
    {
        $this->get(route('password.request'))->assertOk();
    }

    public function test_forgot_password_sends_reset_link_for_eligible_user(): void
    {
        Notification::fake();

        $company = Company::query()->create([
            'name' => 'Reset Co',
            'short_name' => 'resetco',
            'status' => 'active',
        ]);
        $user = User::factory()->create([
            'email' => 'reset@example.com',
            'company_id' => $company->id,
            'allow_login' => true,
        ]);

        $response = $this->post(route('password.email'), [
            'company' => 'resetco',
            'email' => $user->email,
        ]);

        $response->assertRedirect();
        $response->assertSessionHas('status');
        Notification::assertSentTo($user, ResetPassword::class);
    }

    public function test_forgot_password_does_not_reveal_missing_accounts(): void
    {
        Notification::fake();

        $response = $this->post(route('password.email'), [
            'company' => 'missing',
            'email' => 'missing@example.com',
        ]);

        $response->assertRedirect();
        $response->assertSessionHas('status');
        Notification::assertNothingSent();
    }

    public function test_user_can_reset_password_with_valid_token(): void
    {
        $company = Company::query()->create([
            'name' => 'Reset Co',
            'short_name' => 'resetco',
            'status' => 'active',
        ]);
        $user = User::factory()->create([
            'email' => 'reset@example.com',
            'company_id' => $company->id,
            'password' => bcrypt('old-password'),
            'allow_login' => true,
        ]);

        $token = Password::createToken($user);

        $response = $this->post(route('password.store'), [
            'token' => $token,
            'company' => 'resetco',
            'email' => $user->email,
            'password' => 'new-password-1',
            'password_confirmation' => 'new-password-1',
        ]);

        $response->assertRedirect(route('login'));
        $response->assertSessionHas('status');

        $user->refresh();
        $this->assertTrue(Hash::check('new-password-1', $user->password));
    }

    public function test_login_page_shows_forgot_password_link(): void
    {
        $this->get(route('login'))
            ->assertOk()
            ->assertSee('Forgot password?');
    }
}
