<?php

use App\Jobs\SendVerificationEmailJob;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\RateLimiter;

uses(RefreshDatabase::class);

it('rejects registration when honeypot field is filled', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', false);

    $response = $this->from('/register')->post('/register', [
        'email' => 'bot1@example.com',
        'website' => 'https://spam.example',
    ]);

    $response->assertRedirect('/register');
    $response->assertSessionHasErrors('website');
    $this->assertDatabaseMissing('users', ['email' => 'bot1@example.com']);
});

it('throttles excessive registration attempts by ip', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', false);
    config()->set('registration.ip_per_minute_limit', 2);
    config()->set('registration.ip_per_day_limit', 100);

    for ($i = 0; $i < 2; $i++) {
        $this->post('/register', [
            'email' => 'user-rate-' . $i . '@example.com',
        ])->assertRedirect('/setup/password');

        auth()->logout();
    }

    $this->post('/register', [
        'email' => 'user-rate-3@example.com',
    ])->assertStatus(429);

    RateLimiter::clear('register:ip:127.0.0.1');
    RateLimiter::clear('register:ip:daily:127.0.0.1');
});

it('blocks disposable email domains during registration', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', false);
    config()->set('registration.disposable_domains_enabled', true);
    config()->set('disposable_email_domains.domains', ['tempmail.com']);

    $response = $this->from('/register')->post('/register', [
        'email' => 'bot@tempmail.com',
    ]);

    $response->assertRedirect('/register');
    $response->assertSessionHasErrors('email');
    $this->assertDatabaseMissing('users', ['email' => 'bot@tempmail.com']);
});

it('requires turnstile after suspicious registration attempts', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', true);
    config()->set('services.turnstile.site_key', 'site-key');
    config()->set('services.turnstile.secret_key', 'secret-key');

    $response = $this->from('/register')->post('/register', [
        'email' => 'captcha-user@example.com',
    ]);

    $response->assertRedirect('/register');
    $response->assertSessionHasErrors('turnstile_token');
    $this->assertDatabaseMissing('users', ['email' => 'captcha-user@example.com']);
});

it('shows turnstile on the registration screen when enabled', function () {
    config()->set('services.turnstile.enabled', true);
    config()->set('services.turnstile.site_key', 'site-key');
    config()->set('services.turnstile.secret_key', 'secret-key');

    $this->get('/register')
        ->assertOk()
        ->assertSee('cf-turnstile', false);
});

it('rejects registration when turnstile verification fails', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', true);
    config()->set('services.turnstile.site_key', 'site-key');
    config()->set('services.turnstile.secret_key', 'secret-key');

    Http::fake([
        'https://challenges.cloudflare.com/turnstile/v0/siteverify' => Http::response([
            'success' => false,
            'error-codes' => ['invalid-input-response'],
        ], 200),
    ]);

    $response = $this->from('/register')->post('/register', [
        'email' => 'captcha-fail@example.com',
        'turnstile_token' => 'bad-token',
    ]);

    $response->assertRedirect('/register');
    $response->assertSessionHasErrors('turnstile_token');
    $this->assertDatabaseMissing('users', ['email' => 'captcha-fail@example.com']);
    Http::assertSentCount(1);
});

it('enforces verification email cooldown per address', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', false);

    $first = $this->post('/register', [
        'email' => 'cooldown2@example.com',
    ]);

    $first->assertRedirect('/setup/password');
    auth()->logout();

    $response = $this->post('/register', [
        'email' => 'cooldown2@example.com',
    ]);

    $response->assertRedirect('/setup/password');
    $response->assertSessionHas('status', 'Continue with password setup.');
    Queue::assertNothingPushed();
});

it('rejects registration for existing completed emails', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', false);

    User::factory()->create([
        'email' => 'existing@example.com',
        'email_verified_at' => now(),
        'onboarding_step' => 'complete',
        'is_active' => true,
    ]);

    $response = $this->from('/register')->post('/register', [
        'email' => 'existing@example.com',
    ]);

    $response->assertRedirect('/register');
    $response->assertSessionHasErrors('email');
    Queue::assertNothingPushed();
});

it('still allows registration when turnstile passes', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', true);
    config()->set('services.turnstile.site_key', 'site-key');
    config()->set('services.turnstile.secret_key', 'secret-key');

    Http::fake([
        'https://challenges.cloudflare.com/turnstile/v0/siteverify' => Http::response([
            'success' => true,
            'hostname' => 'skinbase.org',
        ], 200),
    ]);

    $response = $this->post('/register', [
        'email' => 'captcha-pass@example.com',
        'turnstile_token' => 'good-token',
    ]);

    $response->assertRedirect('/setup/password');
    $this->assertDatabaseHas('users', ['email' => 'captcha-pass@example.com']);
    Queue::assertNothingPushed();
    Http::assertSentCount(1);
});

it('does not require turnstile when disabled', function () {
    Queue::fake();
    config()->set('services.turnstile.enabled', false);

    $response = $this->post('/register', [
        'email' => 'turnstile-disabled@example.com',
    ]);

    $response->assertRedirect('/setup/password');
    $this->assertDatabaseHas('users', ['email' => 'turnstile-disabled@example.com']);
});
