<?php

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

use FrameworkX\App;
use Middlewares\JwtAuthMiddleware;

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$file = __DIR__ . $path;
if (php_sapi_name() === 'cli-server' && is_file($file)) {
    return false;
}

if (class_exists(Dotenv\Dotenv::class) && file_exists(__DIR__ . '/../.env')) {
    Dotenv\Dotenv::createImmutable(
        dirname(__DIR__),
        null,
        true
    )->safeLoad();
}

error_reporting(E_ALL);

$dsn = $_ENV['DB_DSN'] ?? (function () {
    $host = $_ENV['DB_HOST'] ?? 'localhost';
    $port = $_ENV['DB_PORT'] ?? '5432';
    $name = $_ENV['DB_NAME'] ?? 'postgres';
    return "pgsql:host={$host};port={$port};dbname={$name}";
})();
$dbUser = $_ENV['DB_USER'] ?? 'postgres';
$dbPass = $_ENV['DB_PASSWORD'] ?? '';
$GLOBALS['pdo'] = new \PDO($dsn, $dbUser, $dbPass);
$GLOBALS['pdo']->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

$app = new App();
$authJwt = new JwtAuthMiddleware();

$app->get('/jwthelloworld', $authJwt,\Controllers\HelloController::class);

$app->post('/login', \Controllers\LoginController::class);
$app->post('/register', $authJwt, \Controllers\RegisterController::class);
$app->post('/user/get', $authJwt, \Controllers\UserGetController::class);
$app->post('/user/delete', $authJwt, \Controllers\UserDeleteController::class);

// Public endpoint to create company, user, and wallet in a single transaction
$app->post('/company/user/create', \Controllers\CompanyWithUserController::class);

// Authenticated user profile updates
$app->post('/user/change-email', $authJwt, \Controllers\UserChangeEmailController::class);
$app->post('/user/change-password', $authJwt, \Controllers\UserChangePasswordController::class);

// Commodities (JWT-protected)
$app->post('/commodity/create', $authJwt, \Controllers\CommodityCreateController::class);
$app->post('/commodity/update', $authJwt, \Controllers\CommodityUpdateController::class);
$app->post('/commodity/delete', $authJwt, \Controllers\CommodityDeleteController::class);
$app->get('/commodities', $authJwt, \Controllers\CommoditiesGetController::class);

// CPR registration
$app->post('/cpr/create', $authJwt, \Controllers\RegisterCprController::class);

$app->run();