<?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;

// Import models for route binding
use App\Models\Withdrawal;
use App\Models\Order;
use App\Models\User;
use App\Models\Product;
use App\Models\Commission;
use App\Models\Category;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/dashboard';

    /**
     * The controller namespace for the application.
     *
     * When present, controller route declarations will automatically be prefixed with this namespace.
     *
     * @var string|null
     */
    // protected $namespace = 'App\\Http\\Controllers';

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     */
    public function boot(): void
    {
        // Configurer les rate limiters AVANT les routes
        $this->configureRateLimiting();

        // ============================================================================
        // ROUTE MODEL BINDING - FIX #6 FOR 500 ERRORS
        // ============================================================================
        // Bind route parameters to their corresponding models to prevent null errors
        
        Route::model('withdrawal', Withdrawal::class);
        Route::model('order', Order::class);
        Route::model('user', User::class);
        Route::model('product', Product::class);
        Route::model('commission', Commission::class);
        Route::model('category', Category::class);

        // Implicit route model binding for all routes
        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

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

    /**
     * Configure the rate limiters for the application.
     */
    protected function configureRateLimiting(): void
    {
        // API standard : 60 requêtes/minute
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        // Login : 5 tentatives/minute (protection brute-force)
        RateLimiter::for('login', function (Request $request) {
            return Limit::perMinute(5)
                ->by($request->input('email') . '|' . $request->ip())
                ->response(function () {
                    return back()->withErrors([
                        'email' => 'Trop de tentatives de connexion. Veuillez réessayer dans 1 minute.',
                    ]);
                });
        });

        // Inscription : 3 inscriptions/heure par IP
        RateLimiter::for('register', function (Request $request) {
            return Limit::perHour(3)
                ->by($request->ip())
                ->response(function () {
                    return back()->withErrors([
                        'email' => 'Trop d\'inscriptions depuis cette adresse. Veuillez réessayer plus tard.',
                    ]);
                });
        });

        // Mot de passe oublié : 3 demandes/heure
        RateLimiter::for('password-reset', function (Request $request) {
            return Limit::perHour(3)
                ->by($request->input('email') . '|' . $request->ip())
                ->response(function () {
                    return back()->withErrors([
                        'email' => 'Trop de demandes de réinitialisation. Veuillez réessayer plus tard.',
                    ]);
                });
        });

        // Contact : 5 messages/heure
        RateLimiter::for('contact', function (Request $request) {
            return Limit::perHour(5)
                ->by($request->ip())
                ->response(function () {
                    return back()->withErrors([
                        'message' => 'Trop de messages envoyés. Veuillez réessayer plus tard.',
                    ]);
                });
        });

        // Paiement : 10 tentatives/heure (éviter les fraudes)
        RateLimiter::for('payment', function (Request $request) {
            return Limit::perHour(10)
                ->by($request->user()?->id ?: $request->ip())
                ->response(function () {
                    return back()->withErrors([
                        'payment' => 'Trop de tentatives de paiement. Veuillez réessayer plus tard.',
                    ]);
                });
        });

        // Retrait : 5 demandes/jour
        RateLimiter::for('withdrawal', function (Request $request) {
            return Limit::perDay(5)
                ->by($request->user()?->id ?: $request->ip())
                ->response(function () {
                    return back()->withErrors([
                        'withdrawal' => 'Vous avez atteint la limite de demandes de retrait pour aujourd\'hui.',
                    ]);
                });
        });
    }
}
