<?php

namespace Tests\Feature;

use App\Models\AuditEvent;
use App\Models\BannedIp;
use App\Services\BruteforceGuard;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

class HoneypotSubmitTest extends TestCase
{
    use RefreshDatabase;

    public function test_posting_the_fake_login_is_trapped_bans_and_captures_credentials(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        $res = $this->call('POST', '/wp-login.php', ['log' => 'admin', 'pwd' => 'Hunter2!'], [], [], ['REMOTE_ADDR' => '203.0.113.77']);

        // Served the fake WordPress page (200), NOT a Laravel 419/405 that would unmask the framework.
        $res->assertStatus(200);
        $res->assertSee('WordPress', false);

        // A POST is a login ATTEMPT → logged as such, IP banned, and the guessed credentials captured.
        $e = AuditEvent::where('action', 'security.honeypot_login')->latest('id')->first();
        $this->assertNotNull($e);
        $this->assertSame('admin', $e->meta['tried_user']);
        $this->assertSame('Hunter2!', $e->meta['tried_pass']);
        $this->assertTrue(BannedIp::where('ip', '203.0.113.77')->exists());
    }

    public function test_viewing_a_decoy_logs_but_does_not_ban(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        // GET = merely viewing → logged as a probe, but the source IP is NOT banned (no self-lockout).
        $this->call('GET', '/wp-login.php', [], [], [], ['REMOTE_ADDR' => '203.0.113.82'])->assertStatus(200);

        $this->assertTrue(AuditEvent::where('action', 'security.honeypot_hit')->where('ip', '203.0.113.82')->exists());
        $this->assertFalse(BannedIp::where('ip', '203.0.113.82')->exists());
    }

    public function test_phpmyadmin_and_generic_submits_are_trapped_not_405(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        $this->call('POST', '/phpmyadmin', ['pma_username' => 'root', 'pma_password' => 'toor'], [], [], ['REMOTE_ADDR' => '203.0.113.80'])
            ->assertStatus(200);
        $this->assertSame('root', AuditEvent::where('action', 'security.honeypot_login')->latest('id')->first()->meta['tried_user']);

        $this->call('POST', '/administrator', ['username' => 'sa', 'password' => 'pw'], [], [], ['REMOTE_ADDR' => '203.0.113.81'])
            ->assertStatus(200);
        $this->assertSame('sa', AuditEvent::where('action', 'security.honeypot_login')->latest('id')->first()->meta['tried_user']);
    }

    public function test_banned_ip_stays_in_the_decoy_but_is_blocked_from_the_real_login(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        // A POST login attempt from a non-exempt IP bans it.
        $this->call('POST', '/wp-login.php', ['log' => 'x', 'pwd' => 'y'], [], [], ['REMOTE_ADDR' => '203.0.113.79'])->assertStatus(200);
        $this->assertTrue(BannedIp::where('ip', '203.0.113.79')->exists());

        // The now-banned prober still gets the fake decoy (BlockBannedIp is off for decoys) — kept inside
        // the deception, never told they're blocked.
        $this->call('GET', '/wp-login.php', [], [], [], ['REMOTE_ADDR' => '203.0.113.79'])->assertStatus(200);

        // …but the ban still keeps them off the REAL login (BlockBannedIp -> 403 for a banned guest).
        $this->call('GET', '/login', [], [], [], ['REMOTE_ADDR' => '203.0.113.79'])->assertStatus(403);
    }

    public function test_probe_with_invalid_utf8_does_not_500_still_bans_and_audits(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        // A lone 0x80/0xFF in the User-Agent (which bypasses TrimStrings) is invalid UTF-8. Un-scrubbed
        // it makes the array-cast `meta` column's json_encode throw — an HTTP 500 that unmasks the fake
        // AND aborts the ban, letting an attacker evade the trap by appending a bad byte. Must not happen.
        $res = $this->call(
            'POST', '/wp-login.php',
            ['log' => 'admin', 'pwd' => 'Hunter2!'],
            [], [],
            ['HTTP_USER_AGENT' => "scanner/\x80\xFF", 'REMOTE_ADDR' => '203.0.113.90']
        );

        $res->assertStatus(200);
        $res->assertSee('WordPress', false);

        $e = AuditEvent::where('action', 'security.honeypot_login')->where('ip', '203.0.113.90')->latest('id')->first();
        $this->assertNotNull($e);                          // create() did NOT throw
        $this->assertNotFalse(json_encode($e->meta));      // stored meta is valid UTF-8 / re-encodable
        $this->assertSame('admin', $e->meta['tried_user']);
        $this->assertTrue(BannedIp::where('ip', '203.0.113.90')->exists());
    }

    public function test_a_forged_origin_header_does_not_evade_the_ban(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        // The Origin header is attacker-controlled, so the ban MUST NOT depend on it. A scanner sending a
        // foreign Origin (the obvious evasion attempt) is banned exactly like one that sends none — the
        // POST is still a login attempt on a decoy. Regression guard for the removed Origin-based skip.
        $this->call(
            'POST', '/wp-login.php',
            ['log' => 'admin', 'pwd' => 'x'],
            [], [],
            ['HTTP_ORIGIN' => 'https://evil.example.test', 'REMOTE_ADDR' => '203.0.113.91']
        )->assertStatus(200);

        $this->assertTrue(AuditEvent::where('action', 'security.honeypot_login')->where('ip', '203.0.113.91')->exists());
        $this->assertTrue(BannedIp::where('ip', '203.0.113.91')->exists());
    }

    public function test_ban_still_lands_when_the_audit_write_fails(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        // The instant-ban IS the protection and must NOT be gated by the audit. Drop audit_events so
        // EVERY AuditEvent::create throws (the honeypot row AND banNow's own auth.ip_banned row), then
        // confirm the POST is still banned and still gets the fake body — the ban write (banned_ips) runs
        // before any audit and both are independently guarded, so a broken audit never disarms the trap.
        Schema::drop('audit_events');

        $this->call('POST', '/wp-login.php', ['log' => 'admin', 'pwd' => 'x'], [], [], ['REMOTE_ADDR' => '203.0.113.92'])
            ->assertStatus(200);

        $this->assertTrue(BannedIp::where('ip', '203.0.113.92')->exists());
    }

    public function test_repeated_login_attempts_write_a_single_ban_audit(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        // The honeypot bans on EVERY decoy POST; without the ban-audit dedup, a prober looping the fake
        // login would flood auth.ip_banned. Expect exactly one ban-audit row for the source IP.
        foreach (range(1, 3) as $ignored) {
            $this->call('POST', '/wp-login.php', ['log' => 'a', 'pwd' => 'b'], [], [], ['REMOTE_ADDR' => '203.0.113.93'])
                ->assertStatus(200);
        }

        $this->assertSame(1, AuditEvent::where('action', 'auth.ip_banned')->where('ip', '203.0.113.93')->count());
        $this->assertTrue(BannedIp::where('ip', '203.0.113.93')->exists());
    }

    public function test_audit_cap_stops_new_rows_but_still_bans(): void
    {
        config(['clusev.honeypot.enabled' => true]);
        $ip = '203.0.113.94';

        // Simulate this IP having already blown past the per-hour audit cap (the decoys run without
        // BlockBannedIp, so one source can loop wildcard paths forever). Past the cap: no NEW audit row,
        // but the ban still lands — DoS-bounded logging without weakening protection or the deception.
        Cache::put('honeypot:audit:'.md5($ip), 1000, now()->addHour());

        $this->call('POST', '/wp-login.php', ['log' => 'a', 'pwd' => 'b'], [], [], ['REMOTE_ADDR' => $ip])
            ->assertStatus(200);

        // No NEW probe-audit row past the cap (the ban itself still writes ONE auth.ip_banned row, so we
        // assert on the honeypot action specifically — not every event for this IP).
        $this->assertSame(0, AuditEvent::where('action', 'security.honeypot_login')->where('ip', $ip)->count());
        $this->assertTrue(BannedIp::where('ip', $ip)->exists());
    }

    public function test_a_method_override_does_not_evade_the_ban(): void
    {
        config(['clusev.honeypot.enabled' => true]);

        // A real POST spoofed as PUT via the `_method` body field must NOT dodge the ban — the trap keys
        // off the RAW wire method (getRealMethod), not getMethod()/isMethod() which honor the override.
        $this->call('POST', '/wp-login.php', ['_method' => 'PUT', 'log' => 'admin', 'pwd' => 'x'], [], [], ['REMOTE_ADDR' => '203.0.113.95'])
            ->assertStatus(200);
        $this->assertTrue(BannedIp::where('ip', '203.0.113.95')->exists());
        $this->assertTrue(AuditEvent::where('action', 'security.honeypot_login')->where('ip', '203.0.113.95')->exists());

        // Same via the X-HTTP-Method-Override header vector.
        $this->call('POST', '/wp-login.php', ['log' => 'admin', 'pwd' => 'x'], [], [], ['HTTP_X_HTTP_METHOD_OVERRIDE' => 'PATCH', 'REMOTE_ADDR' => '203.0.113.96'])
            ->assertStatus(200);
        $this->assertTrue(BannedIp::where('ip', '203.0.113.96')->exists());
    }

    public function test_distinct_reason_bans_of_one_ip_are_each_audited(): void
    {
        $guard = app(BruteforceGuard::class);

        // Same reason within the 60s dedup window collapses to one audit; a DISTINCT reason is still
        // audited (the dedup key is per IP+reason). Expect 2 rows: one honeypot, one honeytoken.
        $guard->banNow('203.0.113.97', 'honeypot');
        $guard->banNow('203.0.113.97', 'honeypot');
        $guard->banNow('203.0.113.97', 'honeytoken');

        $this->assertSame(2, AuditEvent::where('action', 'auth.ip_banned')->where('ip', '203.0.113.97')->count());
    }

    public function test_a_reban_after_the_dedup_window_is_audited(): void
    {
        $guard = app(BruteforceGuard::class);
        $ip = '203.0.113.100';

        // The ban-audit dedup is a short 60s window (not the full ban time), so a legitimate later re-ban
        // — e.g. after an operator unban, minutes later — is audited again rather than silently swallowed.
        $guard->banNow($ip, 'honeypot');
        $this->travel(61)->seconds();
        $guard->banNow($ip, 'honeypot');

        $this->assertSame(2, AuditEvent::where('action', 'auth.ip_banned')->where('ip', $ip)->count());
    }
}
