<?php

namespace App\Providers;

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 = '/';

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     */
    public function boot(): void
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        // OTP Request Rate Limiter - Limit by mobile number and IP
        // Allows 3 OTP requests per 15 minutes per mobile number
        RateLimiter::for('otp-request', function (Request $request) {
            $mobile = $request->input('mobile');
            $key = $mobile ? "otp-request:{$mobile}" : "otp-request:{$request->ip()}";
            
            return Limit::perMinutes(15, 3)
                ->by($key)
                ->response(function (Request $request, array $headers) {
                    return response()->json([
                        'error' => 'Too many OTP requests. Please wait before requesting again.'
                    ], 429, $headers);
                });
        });

        // OTP Verification Rate Limiter - Limit by mobile number and IP
        // Allows 5 verification attempts per 15 minutes per mobile number
        RateLimiter::for('otp-verify', function (Request $request) {
            $mobile = $request->input('mobile');
            $key = $mobile ? "otp-verify:{$mobile}" : "otp-verify:{$request->ip()}";
            
            return Limit::perMinutes(15, 5)
                ->by($key)
                ->response(function (Request $request, array $headers) {
                    return response()->json([
                        'error' => 'Too many verification attempts. Please wait before trying again.'
                    ], 429, $headers);
                });
        });

        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }
}
