<?php

declare(strict_types=1);

namespace Builder\Core\Providers;

use Builder\Core\Foundation\Middleware\BuilderAuth;
use Builder\Core\Foundation\Middleware\EnsureMfaIsComplete;
use Builder\Core\Foundation\Middleware\HandleInertiaRequests;
use Builder\Core\Http\Middleware\SetLocale;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

final class AuthServiceProvider extends ServiceProvider
{
    public function boot(Router $router): void
    {
        // Register a dedicated password broker for invite tokens with 24-hour expiry.
        // Using a separate broker avoids interfering with the app's standard password-reset flow.
        config()->set('auth.passwords.builder-invite', [
            'provider' => config('auth.guards.'.BuilderAuth::guard().'.provider', 'users'),
            'table' => config('auth.passwords.users.table', 'password_reset_tokens'),
            'expire' => 1440,
            'throttle' => 60,
        ]);

        RateLimiter::for('builder-login', function (Request $request): Limit {
            return app()->environment('testing')
                ? Limit::perMinute(PHP_INT_MAX)->by('test')
                : Limit::perMinute((int) config('builder.rate_limiting.login', 5))->by($request->ip());
        });

        RateLimiter::for('builder-global', function (Request $request): Limit {
            return app()->environment('testing')
                ? Limit::perMinute(PHP_INT_MAX)->by('test')
                : Limit::perMinute((int) config('builder.rate_limiting.global', 60))
                    ->by(optional($request->user())->getAuthIdentifier() ?? $request->ip());
        });

        $router->aliasMiddleware('builder.auth', BuilderAuth::class);
        $router->aliasMiddleware('builder.locale', SetLocale::class);
        $router->aliasMiddleware('builder.mfa', EnsureMfaIsComplete::class);
        $router->aliasMiddleware('builder.inertia', HandleInertiaRequests::class);
    }
}
