<?php

declare(strict_types=1);

use App\Middleware\CorsMiddleware;
use App\Support\Json;
use Dotenv\Dotenv;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Exception\HttpException;
use Slim\Factory\AppFactory;
use Slim\Middleware\BodyParsingMiddleware;

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

// Load .env (dari root project)
$rootPath = dirname(__DIR__);
if (is_file($rootPath . '/.env')) {
    Dotenv::createImmutable($rootPath)->safeLoad();
}

date_default_timezone_set((string) (($_ENV['APP_TIMEZONE'] ?? null) ?: 'Asia/Jakarta'));

$debug = filter_var($_ENV['APP_DEBUG'] ?? false, FILTER_VALIDATE_BOOLEAN);

$app = AppFactory::create();

// Base path otomatis (mendukung http://localhost/wisuda/be-wisuda/public)
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$basePath = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
if ($basePath === '/' || $basePath === '.') {
    $basePath = '';
}
$app->setBasePath($basePath);

$app->add(new CorsMiddleware());

$bodyParsing = new BodyParsingMiddleware();
// GoWisuda-v2 mengirim body JSON dengan Content-Type text/plain (menghindari preflight CORS).
$bodyParsing->registerBodyParser('text/plain', static function (string $input): array {
    $decoded = json_decode($input, true);
    return is_array($decoded) ? $decoded : [];
});
$app->add($bodyParsing);

// Routes (registrasi)
(require __DIR__ . '/../src/routes.php')($app);

// Error middleware
$errorMiddleware = $app->addErrorMiddleware($debug, true, true);

$errorMiddleware->setDefaultErrorHandler(function (
    Request $request,
    Throwable $exception,
    bool $displayErrorDetails
) use ($app): Response {
    $response = $app->getResponseFactory()->createResponse();

    if ($exception instanceof HttpException) {
        $status = $exception->getCode() ?: 500;
        return Json::error($response, $exception->getMessage(), $status);
    }

    $message = $displayErrorDetails ? $exception->getMessage() : 'Terjadi kesalahan pada server.';
    $errors = $displayErrorDetails ? [
        'type' => $exception::class,
        'file' => $exception->getFile() . ':' . $exception->getLine(),
    ] : null;

    return Json::error($response, $message, 500, $errors);
});

$app->run();
