<?php

namespace Tests\Feature\Auth;

use App\Models\Tenant;
use App\Models\User;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
use Tests\TestCase;

class TenantAdminPasswordResetApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_forgot_password_sends_reset_link_for_tenant_admin(): void
    {
        Notification::fake();

        $tenant = Tenant::factory()->create();
        $user = User::factory()->create([
            'tenant_id' => $tenant->id,
            'role' => 'tenant_admin',
            'email_verified_at' => now(),
        ]);

        $response = $this->postJson(route('api.v1.tenant-auth.forgot-password'), [
            'email' => $user->email,
        ]);

        $response->assertOk();
        Notification::assertSentTo($user, ResetPasswordNotification::class);
    }

    public function test_forgot_password_does_not_disclose_invalid_users(): void
    {
        Notification::fake();

        $user = User::factory()->create([
            'role' => 'user',
            'email_verified_at' => now(),
        ]);

        $response = $this->postJson(route('api.v1.tenant-auth.forgot-password'), [
            'email' => $user->email,
        ]);

        $response->assertOk();
        Notification::assertNothingSent();
    }

    public function test_reset_password_updates_tenant_admin_password(): void
    {
        $tenant = Tenant::factory()->create();
        $user = User::factory()->create([
            'tenant_id' => $tenant->id,
            'role' => 'tenant_admin',
            'email_verified_at' => now(),
        ]);

        $token = Password::broker()->createToken($user);

        $response = $this->postJson(route('api.v1.tenant-auth.reset-password'), [
            'token' => $token,
            'email' => $user->email,
            'password' => 'NewPassword123!',
            'password_confirmation' => 'NewPassword123!',
        ]);

        $response->assertOk();

        $user->refresh();
        $this->assertTrue(Hash::check('NewPassword123!', $user->password));
    }

    public function test_reset_password_blocks_non_admin_users(): void
    {
        $user = User::factory()->create([
            'role' => 'user',
            'email_verified_at' => now(),
        ]);

        $token = Password::broker()->createToken($user);

        $response = $this->postJson(route('api.v1.tenant-auth.reset-password'), [
            'token' => $token,
            'email' => $user->email,
            'password' => 'NewPassword123!',
            'password_confirmation' => 'NewPassword123!',
        ]);

        $response->assertStatus(422);
        $response->assertJsonValidationErrors('email');
    }
}
