<?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',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'restrict.origin' => \App\Http\Middleware\RestrictOrigin::class,
            'redirect.browser' => \App\Http\Middleware\RedirectBrowserToHomepage::class,
        ]);

        // Remove Laravel's built-in HandleCors — RestrictOrigin handles CORS entirely
        $middleware->remove(\Illuminate\Http\Middleware\HandleCors::class);

        // RestrictOrigin must be GLOBAL (before routing) so OPTIONS preflight is intercepted
        // before Symfony's router auto-handles it without CORS headers
        $middleware->prepend(\App\Http\Middleware\RestrictOrigin::class);

        // Browser redirect only for API routes
        $middleware->api(prepend: [
            \App\Http\Middleware\RedirectBrowserToHomepage::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Always return JSON responses for API routes
        $exceptions->render(function (Throwable $e, $request) {
            // Only handle API routes
            if ($request->is('api/*')) {
                $statusCode = method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500;

                // Default error message
                $message = $e->getMessage() ?: 'Server Error';

                // Handle specific exception types
                if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
                    $statusCode = 405;
                    $message = 'Method not allowed for this route';
                } elseif ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
                    $statusCode = 404;
                    $message = 'Route not found';
                } elseif ($e instanceof \Illuminate\Auth\AuthenticationException) {
                    $statusCode = 401;
                    $message = 'Unauthenticated';
                } elseif ($e instanceof \Illuminate\Auth\Access\AuthorizationException) {
                    $statusCode = 403;
                    $message = 'Unauthorized';
                } elseif ($e instanceof \Illuminate\Validation\ValidationException) {
                    // Let Laravel handle validation exceptions normally
                    return null;
                } elseif ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
                    $statusCode = 404;
                    $message = class_basename($e->getModel()) . ' not found.';
                }

                // Don't expose sensitive error details in production
                if (config('app.debug') === false && $statusCode === 500) {
                    $message = 'Internal Server Error';
                }

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

            // Let Laravel handle non-API routes normally
            return null;
        });
    })->create();
