<?php

namespace Tests\Unit;

use App\Models\GuestPolicySetting;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Tests\TestCase;

class RateLimitConfigTest extends TestCase
{
    use RefreshDatabase;

    public function test_tenant_api_rate_limiter_allows_higher_throughput(): void
    {
        $request = Request::create('/api/v1/tenant/events', 'GET', [], [], [], [
            'REMOTE_ADDR' => '10.0.0.1',
        ]);
        $request->attributes->set('tenant_id', 42);

        $limiter = RateLimiter::limiter('tenant-api');

        $this->assertNotNull($limiter);

        $limit = $limiter($request);

        $this->assertInstanceOf(Limit::class, $limit);
        $this->assertSame(600, $limit->maxAttempts);
    }

    public function test_guest_api_rate_limiter_allows_higher_throughput(): void
    {
        $request = Request::create('/api/v1/events/sample', 'GET', [], [], [], [
            'REMOTE_ADDR' => '10.0.0.2',
        ]);

        $limiter = RateLimiter::limiter('guest-api');

        $this->assertNotNull($limiter);

        $limit = $limiter($request);

        $this->assertInstanceOf(Limit::class, $limit);
        $this->assertSame(300, $limit->maxAttempts);
    }

    public function test_guest_policy_defaults_follow_join_token_limits(): void
    {
        $accessLimit = 300;
        $downloadLimit = 120;

        config([
            'join_tokens.access_limit' => $accessLimit,
            'join_tokens.download_limit' => $downloadLimit,
        ]);

        GuestPolicySetting::query()->delete();
        GuestPolicySetting::flushCache();

        $settings = GuestPolicySetting::current();

        $this->assertSame($accessLimit, $settings->join_token_access_limit);
        $this->assertSame($downloadLimit, $settings->join_token_download_limit);
    }
}
