<?php

use App\Domain\PluginSdk\Services\PluginLoader;
use App\Http\Middleware\AccountLockout;
use App\Http\Middleware\AdminIpWhitelist;
use App\Http\Middleware\DetectResellerBranding;
use App\Http\Middleware\EnforceLicense;
use App\Http\Middleware\EnsureUserIsAdmin;
use App\Http\Middleware\EnsureUserIsCustomer;
use App\Http\Middleware\EnsureUserIsReseller;
use App\Http\Middleware\HandleInertiaRequests;
use App\Http\Middleware\PluginSandbox;
use App\Http\Middleware\SecurityHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        apiPrefix: 'api',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // Security headers applied globally (web + API)
        $middleware->append(SecurityHeaders::class);

        $middleware->web(append: [
            // DetectResellerBranding MUST run before HandleInertiaRequests so
            // Inertia share() can read $request->attributes->get('reseller_branding')
            // from custom-domain (white-label) requests.
            DetectResellerBranding::class,
            HandleInertiaRequests::class,
            AddLinkHeadersForPreloadedAssets::class,
        ]);

        // EnforceLicense web group başına eklenir → auth/admin middleware'lerinden ÖNCE çalışır
        // Yani lisans yoksa user login bile yapamaz; direkt /lisans/satin-al'a yönlendirilir.
        $middleware->web(prepend: [
            EnforceLicense::class,
        ]);

        $middleware->alias([
            'admin' => EnsureUserIsAdmin::class,
            'customer' => EnsureUserIsCustomer::class,
            'reseller' => EnsureUserIsReseller::class,
            'lockout' => AccountLockout::class,
            'plugin.sandbox' => PluginSandbox::class,
            'license' => EnforceLicense::class,
            // Opt-in admin paneli IP whitelist — server_settings tablosunda
            // admin_ip_whitelist_enabled=1 set edilirse aktif olur.
            'admin.ip' => AdminIpWhitelist::class,
        ]);
    })
    ->booted(function (Illuminate\Contracts\Foundation\Application $app) {
        $app->make(PluginLoader::class)->loadAll();
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // Inertia error pages — Pages/Error.vue render eder
        // 401/403/404/419/429/500/503 için modern UI
        $exceptions->respond(function (\Symfony\Component\HttpFoundation\Response $response, \Throwable $exception, \Illuminate\Http\Request $request) {
            $status = $response->getStatusCode();

            // JSON/API request'lerinde değişmez (default Laravel handler)
            if ($request->expectsJson() || $request->is('api/*')) {
                return $response;
            }

            // Sadece 4xx/5xx için custom Inertia page
            if (! in_array($status, [401, 403, 404, 419, 422, 429, 500, 502, 503], true)) {
                return $response;
            }

            // Debug modunda whoops sayfası göster (development friendly)
            if (config('app.debug') && $status === 500) {
                return $response;
            }

            return \Inertia\Inertia::render('Error', [
                'status' => $status,
                'message' => $status === 419 ? 'Oturum süresi doldu' : ($exception->getMessage() ?: ''),
            ])->toResponse($request)->setStatusCode($status);
        });
    })->create();
