<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Infrastructure\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use ImovelZapAi\SuperAdmin\Application\Actions\EndImpersonationAction;
use ImovelZapAi\SuperAdmin\Application\Actions\ManageIncidentAction;
use ImovelZapAi\SuperAdmin\Application\Actions\PlatformChangeTenantPlanAction;
use ImovelZapAi\SuperAdmin\Application\Actions\PlatformChangeTenantStatusAction;
use ImovelZapAi\SuperAdmin\Application\Actions\PlatformCreateTenantAction;
use ImovelZapAi\SuperAdmin\Application\Actions\PlatformLoginAction;
use ImovelZapAi\SuperAdmin\Application\Actions\PlatformLogoutAction;
use ImovelZapAi\SuperAdmin\Application\Actions\RecordSupportActionAction;
use ImovelZapAi\SuperAdmin\Application\Actions\StartImpersonationAction;
use ImovelZapAi\SuperAdmin\Application\Queries\GetPlatformMetricsQuery;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformAuditLogger;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformHealthProbe;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformSettingsStore;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformTotp;

final class SuperAdminServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $configPath = base_path('config/superadmin.php');
        if (is_file($configPath)) {
            $this->mergeConfigFrom($configPath, 'superadmin');
        }

        $this->app->singleton(PlatformAuditLogger::class);
        $this->app->singleton(PlatformTotp::class);
        $this->app->singleton(PlatformSettingsStore::class);
        $this->app->singleton(PlatformHealthProbe::class);
        $this->app->singleton(GetPlatformMetricsQuery::class);
        $this->app->singleton(PlatformLoginAction::class);
        $this->app->singleton(PlatformLogoutAction::class);
        $this->app->singleton(PlatformCreateTenantAction::class);
        $this->app->singleton(PlatformChangeTenantStatusAction::class);
        $this->app->singleton(PlatformChangeTenantPlanAction::class);
        $this->app->singleton(StartImpersonationAction::class);
        $this->app->singleton(EndImpersonationAction::class);
        $this->app->singleton(RecordSupportActionAction::class);
        $this->app->singleton(ManageIncidentAction::class);
    }

    public function boot(): void
    {
        RateLimiter::for('platform', function (Request $request) {
            $key = Auth::guard('platform')->id() ?: $request->ip();

            return Limit::perMinute(60)->by((string) $key);
        });

        Route::middleware('web')->group(__DIR__.'/../Routes/web.php');
        Route::middleware('api')->prefix('api')->group(__DIR__.'/../Routes/api.php');
    }
}
