<?php

use App\Http\Middleware\CheckMenuEnabled;
use App\Http\Middleware\EnsureXsrfToken;
use App\Http\Middleware\HandleAppearance;
use App\Http\Middleware\HandleInertiaRequests;
use App\Http\Middleware\LogCsrfFailure;
use App\Http\Middleware\RoleMiddleware;
use App\Http\Middleware\SecurityHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets;
use Inertia\Inertia;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->encryptCookies(except: ['appearance', 'sidebar_state']);

        $middleware->validateCsrfTokens(except: [
            'logout',
            'topup/ipaymu/*',
            'topup/duitku/*',
            'topup/tripay/*',
            'topup/pakasir/*',
            'api/*',
            'admin/backup/download/*',
            'admin/backup/restore/*',
        ]);

        $middleware->web(append: [
            SecurityHeaders::class,
            EnsureXsrfToken::class,
            HandleAppearance::class,
            HandleInertiaRequests::class,
            AddLinkHeadersForPreloadedAssets::class,
            LogCsrfFailure::class,
            \App\Http\Middleware\EnsureUserIsActivated::class,
        ]);

        $middleware->alias([
            'role' => RoleMiddleware::class,
            'menu.enabled' => CheckMenuEnabled::class,
            'activated' => \App\Http\Middleware\EnsureUserIsActivated::class,
            'customThrottle' => \App\Http\Middleware\CustomThrottle::class,
        ]);

        // Redirect unauthenticated users to login page
        $middleware->redirectGuestsTo('/login');

        // Redirect authenticated users to dashboard when accessing guest pages (login/register)
        $middleware->redirectUsersTo('/dashboard');
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (NotFoundHttpException $e, $request) {
            return Inertia::render('errors/404')->toResponse($request)->setStatusCode(404);
        });

        $exceptions->render(function (\Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException $e, $request) {
            $retryAfter = $e->getHeaders()['Retry-After'] ?? 60;
            $friendlyMessage = "Terlalu banyak permintaan. Silakan tunggu {$retryAfter} detik sebelum mencoba lagi.";

            if ($request->header('X-Inertia')) {
                return back()->withErrors([
                    'error' => $friendlyMessage,
                ])->setStatusCode(429);
            }

            return response()->json([
                'message' => $friendlyMessage,
                'retry_after' => (int) $retryAfter,
            ], 429);
        });
    })->create();
