<?php
declare(strict_types=1);

use Slim\App;
use Slim\Middleware\ContentLengthMiddleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;

require_once __DIR__ . '/config.php';

return function (App $app) {
    // CORS middleware - must run first, before ANY other middleware
    $app->add(function (Request $request, RequestHandler $handler) {
        $env = APP_ENV;
          // If in development, apply CORS headers
        if ($env === 'development') {
            // Clear any previous headers to avoid duplicates
            // Only for headers we're going to set
            if (function_exists('header_remove')) {
                header_remove('Access-Control-Allow-Origin');
                header_remove('Access-Control-Allow-Headers');
                header_remove('Access-Control-Allow-Methods');
                header_remove('Access-Control-Allow-Credentials');
                header_remove('Access-Control-Max-Age');
            }
            
            // Hard-coded CORS headers for simplicity and reliability
            header('Access-Control-Allow-Origin: http://localhost:3000');
            header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Origin, Accept');
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS');
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 3600');
            header('Vary: Origin'); // Important for proper caching with CORS
            
            // Handle OPTIONS request specially (preflight)
            if ($request->getMethod() === 'OPTIONS') {
                // Log for debugging
                error_log('[CORS] Handling OPTIONS request by sending headers and returning early');
                
                // Return 200 OK with no content for OPTIONS
                header('Content-Type: text/plain; charset=UTF-8');
                header('Content-Length: 0');
                http_response_code(200);
                exit(0); // Exit immediately for OPTIONS
            }
            
            error_log('[CORS] Added headers to ' . $request->getMethod() . ' request: ' . $request->getUri()->getPath());
        }
        
        // For non-OPTIONS requests, pass to the next handler
        $response = $handler->handle($request);
        return $response;
    });

    // Parse json, form data and xml
    $app->addBodyParsingMiddleware();
    
    // Add Content-Length header
    $app->add(new ContentLengthMiddleware());

    // Add routing middleware
    $app->addRoutingMiddleware();
    
    // Error handling middleware
    $errorMiddleware = $app->addErrorMiddleware(true, true, true);

    // Custom error handler that returns JSON instead of HTML for all errors
    $errorHandler = $errorMiddleware->getDefaultErrorHandler();
    $errorHandler->forceContentType('application/json');
    $errorHandler->registerErrorRenderer('application/json', function ($exception, $displayErrorDetails) {
        return [
            'success' => false,
            'message' => $displayErrorDetails ? $exception->getMessage() : 'An error occurred',
            'code' => $exception->getCode(),
            'file' => $displayErrorDetails ? $exception->getFile() : null,
            'line' => $displayErrorDetails ? $exception->getLine() : null,
            'trace' => $displayErrorDetails ? $exception->getTraceAsString() : null
        ];
    });
    
    return $app;
};
