<?php

namespace App\Providers;

use App\Models\ClientDomain;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to your application's "home" route.
     *
     * Typically, users are redirected here after authentication.
     *
     * @var string
     */
    public const HOME = '/clientarea/dashboard';

    public const ADMIN_HOME = '/admin/dashboard';

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     */
    public function boot(): void
    {
        // Route model binding
        Route::bind('domain', function ($value) {
            return ClientDomain::findOrFail($value);
        });

        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        // PRC-167 SEC-Critical — admin login route-level rate limit
        // (defense-in-depth on top of LoginRequest's email|ip throttleKey).
        // Distributed password spraying (1 password × 1000 email) blocks per-IP
        // bucket at 20/min and per-email at 5/min — bypass requires both
        // X-Forwarded-For rotation AND email enumeration.
        RateLimiter::for('admin-login', function (Request $request) {
            // PRC-581 — non-production (local/dev) ortamlarda dev rahatlığı için
            // bol limit; PRODUCTION'da PRC-167 sıkı değerleri AYNEN korunur.
            if (! app()->environment('production')) {
                return Limit::perMinute(100)->by($request->ip());
            }

            return [
                Limit::perMinute(20)->by($request->ip()),
                Limit::perMinute(5)->by(strtolower((string) $request->input('email'))),
            ];
        });

        // PRC-166 SEC-Critical — 2FA verify endpoint rate limit (admin + client).
        // 6 hane TOTP kodu için brute-force koruması. Yetkili kullanıcı 5
        // başarısız deneme sonrası 1 dakika kilitlenir. Hedef: ~3/10^6 başarı
        // ihtimali × sınırsız → 5 deneme limit'i ile pratikte imkansız.
        // Per-user bucket (auth'd context) + per-IP fallback.
        RateLimiter::for('2fa-verify', function (Request $request) {
            $userKey = $request->user('admin')?->id
                ?? $request->user('client')?->id
                ?? null;

            // PRC-581 — non-production'da bol; PRODUCTION'da PRC-166 sıkı korunur.
            if (! app()->environment('production')) {
                return Limit::perMinute(100)->by($userKey ? 'user:' . $userKey : 'ip:' . $request->ip());
            }

            return [
                $userKey
                    ? Limit::perMinute(5)->by('user:' . $userKey)
                    : Limit::perMinute(5)->by('ip:' . $request->ip()),
                Limit::perMinute(20)->by($request->ip()), // anti-rotation cap
            ];
        });

        // PRC-581 — store/client login rate limit (defense-in-depth). Eskiden
        // route'ta inline `throttle:5,1`'di; named limiter'a alındı ki ortam-bazlı
        // olabilsin. PRODUCTION: 5/dk/IP (eski değer); non-production: bol.
        RateLimiter::for('store-login', function (Request $request) {
            return Limit::perMinute(app()->environment('production') ? 5 : 100)
                ->by($request->ip());
        });

        $this->routes(function () {
            // PRC-867 — kurulum sihirbazı (minimal middleware, DB'siz).
            Route::middleware('install')
                ->group(base_path('routes/install.php'));

            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::prefix('storeapi')
                ->group(base_path('routes/storeapi.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }
}
