<?php
/**
 * FreshCloud Mail — bridge bootstrap + router
 *
 * Acts as a router: nginx routes all /api/email/* requests here with
 * PATH_INFO set to the path after /api/email. We dispatch to the
 * appropriate compose/<endpoint>.php or top-level <endpoint>.php.
 */

declare(strict_types=1);

if (!defined('FRESHCLOUD_MAIL_BOOTSTRAPPED')) {
    define('FRESHCLOUD_MAIL_BOOTSTRAPPED', true);

    // 1. Composer autoloader (only if vendor/ exists)
    $autoload = __DIR__ . '/../../vendor/autoload.php';
    if (file_exists($autoload)) {
        require_once $autoload;
    }
}

// 2. Parse PATH_INFO into parts
$path_info = $_SERVER['PATH_INFO'] ?? '';
$path_info = ltrim($path_info, '/');
$path_info = rtrim($path_info, '/');
$path_parts = $path_info === '' ? [] : explode('/', $path_info);

// 3. Helpers (defined at top level so require()d handlers can call them)
if (!function_exists('freshcloud_mail_composer')) {
    function freshcloud_mail_composer(?string $userId = null, ?string $accountId = null): ?\FreshCloud\Mail\Compose\Composer
    {
        return null;
    }
}

if (!function_exists('freshcloud_mail_json')) {
    function freshcloud_mail_json(int $status, array $payload): void
    {
        http_response_code($status);
        header('Content-Type: application/json');
        header('X-FreshCloud-Mail: v0.1.0-test');
        echo json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        exit;
    }
}

if (!function_exists('freshcloud_mail_error')) {
    function freshcloud_mail_error(int $status, string $error, string $message): void
    {
        freshcloud_mail_json($status, [
            'error' => $error,
            'message' => $message,
            'timestamp' => gmdate('c'),
        ]);
    }
}

// 4. Router
$dispatched = false;
$route_params = [];
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

// Known actions that are NOT draft ids
$known_compose_actions = ['start', 'save', 'resume', 'delete', 'send'];

// 4a. /api/email/ -> discovery
if (empty($path_parts)) {
    require __DIR__ . '/discovery.php';
    $dispatched = true;
}
// 4b. /api/email/<endpoint> -> top-level
elseif (count($path_parts) === 1) {
    $endpoint = $path_parts[0];
    // accounts uses the new list endpoint
    if ($endpoint === 'accounts' && $method === 'GET') {
        require __DIR__ . '/accounts-list.php';
        $dispatched = true;
    } else {
        $file = __DIR__ . '/' . $endpoint . '.php';
        if (file_exists($file)) {
            require $file;
            $dispatched = true;
        }
    }
}
// 4c. /api/email/compose/{action} -> compose action with no draft id
elseif (count($path_parts) === 2 && $path_parts[0] === 'compose' && in_array($path_parts[1], $known_compose_actions, true)) {
    $action = $path_parts[1];
    $file = __DIR__ . '/compose/' . $action . '.php';
    if (file_exists($file)) {
        require $file;
        $dispatched = true;
    }
}
// 4d. /api/email/compose/{id}/{action} -> compose with draft id and action
elseif (count($path_parts) === 3 && $path_parts[0] === 'compose') {
    $route_params = ['id' => $path_parts[1]];
    $action = $path_parts[2];
    $file = __DIR__ . '/compose/' . $action . '.php';
    if (file_exists($file)) {
        require $file;
        $dispatched = true;
    }
}
// 4e. /api/email/compose/{id} -> compose with draft id, action by method
elseif (count($path_parts) === 2 && $path_parts[0] === 'compose') {
    $route_params = ['id' => $path_parts[1]];
    if ($method === 'GET') {
        $action = 'resume';
    } elseif ($method === 'DELETE') {
        $action = 'delete';
    } elseif ($method === 'PUT') {
        $action = 'save';
    } else {
        freshcloud_mail_error(405, 'method_not_allowed', "Method $method not allowed for /api/email/compose/{id}");
    }
    $file = __DIR__ . '/compose/' . $action . '.php';
    if (file_exists($file)) {
        require $file;
        $dispatched = true;
    }
}
// 4f. /api/email/messages/{id}/body -> full message body
elseif (count($path_parts) === 3 && $path_parts[0] === 'messages' && $path_parts[2] === 'body') {
    $route_params = ['id' => $path_parts[1]];
    $_SERVER['FRESH_ROUTE_PARAMS'] = $route_params;
    require __DIR__ . '/messages-body.php';
    $dispatched = true;
}
// 4g. /api/email/messages/{id}/flags -> set flags (PATCH)
elseif (count($path_parts) === 3 && $path_parts[0] === 'messages' && $path_parts[2] === 'flags') {
    $route_params = ['id' => $path_parts[1]];
    $_SERVER['FRESH_ROUTE_PARAMS'] = $route_params;
    require __DIR__ . '/messages-flags.php';
    $dispatched = true;
}
// 4h. /api/email/messages/{id}/move -> move to folder (PATCH)
elseif (count($path_parts) === 3 && $path_parts[0] === 'messages' && $path_parts[2] === 'move') {
    $route_params = ['id' => $path_parts[1]];
    $_SERVER['FRESH_ROUTE_PARAMS'] = $route_params;
    require __DIR__ . '/messages-move.php';
    $dispatched = true;
}
// 4i. /api/email/messages/{id} -> delete (DELETE)
elseif (count($path_parts) === 2 && $path_parts[0] === 'messages' && $method === 'DELETE') {
    $route_params = ['id' => $path_parts[1]];
    $_SERVER['FRESH_ROUTE_PARAMS'] = $route_params;
    require __DIR__ . '/messages-delete.php';
    $dispatched = true;
}
// 4j. /api/email/accounts/{id}/active -> switch account (PUT)
elseif (count($path_parts) === 3 && $path_parts[0] === 'accounts' && $path_parts[2] === 'active' && $method === 'PUT') {
    $route_params = ['id' => $path_parts[1]];
    $_SERVER['FRESH_ROUTE_PARAMS'] = $route_params;
    require __DIR__ . '/accounts-switch.php';
    $dispatched = true;
}
// 4k. /api/email/accounts/{id}/storage -> storage stats (GET)
elseif (count($path_parts) === 3 && $path_parts[0] === 'accounts' && $path_parts[2] === 'storage' && $method === 'GET') {
    $route_params = ['id' => $path_parts[1]];
    $_SERVER['FRESH_ROUTE_PARAMS'] = $route_params;
    require __DIR__ . '/accounts-storage.php';
    $dispatched = true;
}
// 4l. /api/email/accounts/{id}/refresh -> force refresh (POST)
elseif (count($path_parts) === 3 && $path_parts[0] === 'accounts' && $path_parts[2] === 'refresh' && $method === 'POST') {
    $route_params = ['id' => $path_parts[1]];
    $_SERVER['FRESH_ROUTE_PARAMS'] = $route_params;
    require __DIR__ . '/accounts-refresh.php';
    $dispatched = true;
}

if (!$dispatched) {
    http_response_code(404);
    header('Content-Type: application/json');
    header('X-FreshCloud-Mail: v0.1.0-test');
    echo json_encode([
        'error' => 'not_found',
        'message' => "No handler for path: /$path_info",
        'timestamp' => gmdate('c'),
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit;
}
