<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        apiPrefix: '',
        // health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // HttpOnly cookie → Bearer for Sanctum (SPA on mykopkb.com → api.mykopkb.com)
        $middleware->api(prepend: [
            \App\Http\Middleware\AuthenticateFromCookie::class,
        ]);

        // Single session enforcement for authenticated routes
        $middleware->alias([
            'single.session' => \App\Http\Middleware\SingleSessionMiddleware::class,
            'block.api.tools' => \App\Http\Middleware\BlockApiToolsMiddleware::class,
            'api.key.auth' => \App\Http\Middleware\ApiKeyAuthenticationMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Customize authorization exception message to Malay
        $exceptions->render(function (Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tindakan ini tidak dibenarkan.',
                ], 403);
            }
        });

        // Also handle AuthorizationException for backward compatibility
        $exceptions->render(function (Illuminate\Auth\Access\AuthorizationException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tindakan ini tidak dibenarkan.',
                ], 403);
            }
        });

        // Handle Model Not Found exceptions (404 errors)
        $exceptions->render(function (Illuminate\Database\Eloquent\ModelNotFoundException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Data tidak dijumpai.',
                ], 404);
            }
        });

        // Handle Validation exceptions (422 errors)
        $exceptions->render(function (Illuminate\Validation\ValidationException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Data tidak sah.',
                    'errors' => $e->errors(),
                ], 422);
            }
        });

        // Handle Authentication exceptions (401 errors)
        $exceptions->render(function (Illuminate\Auth\AuthenticationException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda perlu log masuk terlebih dahulu.',
                ], 401);
            }
            return redirect()->guest('/login');
        });

        // Handle Method Not Allowed exceptions (405 errors)
        $exceptions->render(function (Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Kaedah HTTP tidak dibenarkan.',
                ], 405);
            }
        });

        // Handle Route Not Found exceptions (404 errors)
        $exceptions->render(function (Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Halaman tidak dijumpai.',
                ], 404);
            }
        });

        // Handle Too Many Requests exceptions (429 errors)
        $exceptions->render(function (Illuminate\Http\Exceptions\ThrottleRequestsException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Terlalu banyak permintaan. Sila cuba lagi nanti.',
                ], 429);
            }
        });

        // Handle general exceptions (500 errors) - only in production
        $exceptions->render(function (Throwable $e, $request) {
            if ($request->expectsJson()) {
                $message = app()->environment('production')
                    ? 'Ralat dalaman pelayan. Sila hubungi pentadbir sistem.'
                    : $e->getMessage();

                return response()->json([
                    'success' => false,
                    'message' => $message,
                ], 500);
            }
        });
    })->create();
