<?php

namespace Tests\Feature;

use App\Livewire\Auth\ForgotPassword;
use App\Livewire\Auth\ResetPassword;
use App\Models\User;
use App\Notifications\QueuedResetPassword as ResetPasswordNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
use Livewire\Livewire;
use Tests\TestCase;

class EmailResetTest extends TestCase
{
    use RefreshDatabase;

    public function test_link_option_hidden_when_mailer_is_log(): void
    {
        config(['mail.default' => 'log']);
        $this->assertFalse((new ForgotPassword)->mailEnabled());
    }

    public function test_send_link_dispatches_notification_when_mail_configured(): void
    {
        config(['mail.default' => 'smtp']);
        Notification::fake();
        $user = User::factory()->create(['email' => 'admin@clusev.local']);

        Livewire::test(ForgotPassword::class)
            ->set('email', 'admin@clusev.local')
            ->call('sendResetLink')
            ->assertHasNoErrors();

        Notification::assertSentTo($user, ResetPasswordNotification::class);
    }

    public function test_reset_password_with_token_sets_new_password(): void
    {
        $user = User::factory()->create();
        $token = Password::createToken($user);

        Livewire::test(ResetPassword::class, ['token' => $token])
            ->set('email', $user->email)
            ->set('password', 'NewPassw0rd123')->set('password_confirmation', 'NewPassw0rd123')
            ->call('resetPassword')->assertHasNoErrors();

        $this->assertTrue(Hash::check('NewPassw0rd123', $user->fresh()->password));
    }
}
