<?php

use Slim\Factory\AppFactory;
use Tuupola\Middleware\CorsMiddleware;
use Slim\Exception\HttpNotFoundException; 
use Psr\Http\Message\ServerRequestInterface as Request;

require __DIR__ . '/../vendor/autoload.php';

// Create App
$app = AppFactory::create();

// Add CORS Middleware
$app->add(new Tuupola\Middleware\CorsMiddleware([
    "origin" => ["*"], // Allow all origins
    "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], // Allowed methods
    "headers.allow" => ["Content-Type", "Authorization"], // Allowed headers
    "headers.expose" => ["Content-Type", "Authorization"], // Exposed headers
    "credentials" => true, // Allow credentials
    "cache" => 86400, // Cache preflight response
]));


// Define a custom error handler for 404 Not Found
$errorMiddleware = $app->addErrorMiddleware(true, true, true);

$errorMiddleware->setErrorHandler(
    HttpNotFoundException::class,
    function (Request $request, Throwable $exception, bool $displayErrorDetails) use ($app) {
        $response = $app->getResponseFactory()->createResponse();
        $response->getBody()->write("BLACKFORCE - V4");
        return $response->withStatus(404)
                        ->withHeader('Content-Type', 'text/plain');
    }
);

// Define routes
$routes = require __DIR__ . '/../routes/routes.php';
$routes($app);

// Run the app
$app->run();
