<?php
namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

final class GatewayRateLimitServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $key = fn(Request $r) => (string) optional($r->attributes->get('apiKey'))->id ?: $r->ip();
        RateLimiter::for('api-read', fn(Request $r) => Limit::perMinute(120)->by('read:'.$key($r)));
        RateLimiter::for('payment-create', fn(Request $r) => Limit::perMinute(30)->by('payment:'.$key($r)));
        RateLimiter::for('estimate', fn(Request $r) => Limit::perMinute(60)->by('estimate:'.$key($r)));
        RateLimiter::for('payout-create', fn(Request $r) => [
            Limit::perMinute(5)->by('payout-minute:'.$key($r)),
            Limit::perDay((int) config('gateway.security.payout_daily_request_limit', 25))->by('payout-day:'.$key($r)),
        ]);
        RateLimiter::for('dashboard-login', fn(Request $r) => [
            Limit::perMinute(5)->by('login-ip:'.$r->ip()),
            Limit::perMinute(5)->by('login-account:'.hash('sha256', strtolower((string) $r->input('email')))),
        ]);
        RateLimiter::for('provider-webhook', fn(Request $r) => Limit::perMinute(600)->by('provider:'.$r->route('provider').':'.$r->ip()));
    }
}
