<?php

namespace Tests\Feature\Auth;

use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role;
use App\Domains\Notification\Events\PasswordResetRequested;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;

class AdminAppResetPasswordControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_creates_an_attempt_for_a_tenant_bound_adminapp_user(): void
    {
        Event::fake([PasswordResetRequested::class]);
        Role::query()->create([
            'codigo' => RoleCode::AdminApp->value,
            'nombre' => 'AdminApp',
        ]);
        $tenant = Tenant::query()->create([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'store.acme.test',
        ]);
        $user = User::factory()->create([
            'email' => 'admin@example.com',
            'rol_codigo' => RoleCode::AdminApp->value,
            'tenant_codigo' => $tenant->codigo,
        ]);

        $this->postJson('/api/v1/adminapp/password/reset-attempts', [
            'email' => ' ADMIN@EXAMPLE.COM ',
        ])->assertAccepted()->assertJsonPath('status', ResetPasswordAttempt::STATUS_PENDING);

        $attempt = $user->resetPasswordAttempts()->sole();
        Event::assertDispatched(
            PasswordResetRequested::class,
            fn (PasswordResetRequested $event): bool => $event->attemptId === $attempt->id
                && $event->tenantCode === $tenant->codigo
                && $event->channel === PasswordResetRequested::CHANNEL_ADMINAPP,
        );
    }

    public function test_it_does_not_create_an_attempt_for_a_non_adminapp_user(): void
    {
        Event::fake([PasswordResetRequested::class]);

        $this->postJson('/api/v1/adminapp/password/reset-attempts', [
            'email' => User::factory()->create()->email,
        ])->assertAccepted()->assertJsonPath('status', ResetPasswordAttempt::STATUS_PENDING);

        $this->assertDatabaseCount('reset_password_attempts', 0);
        Event::assertNotDispatched(PasswordResetRequested::class);
    }
}
