<?php
/**
 * FreshCloud Mail — list folders for an account
 * GET /api/email/folders?account_id=...
 *
 * Returns: 200 OK with array of FolderInfo
 */

declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

$accountId = $_GET['account_id'] ?? null;
$userId = $_GET['user_id'] ?? 'admin@freshvibeapps.local';

if (!$accountId) {
    freshcloud_mail_error(400, 'missing_account_id', 'account_id is required');
}

$logger = freshcloud_mail_logger();
$pb = freshcloud_mail_pb();

// Use ImapCommands directly — Composer isn't needed for read operations
$imapCommands = new \FreshCloud\Mail\ImapCommands\InMemoryImapCommands($pb, $logger);

try {
    $folders = $imapCommands->listFolders($userId, $accountId);

    $payload = array_map(fn($f) => [
        'name' => $f->name,
        'delimiter' => $f->delimiter,
        'message_count' => $f->messageCount,
        'unseen_count' => $f->unseenCount,
        'uid_validity' => $f->uidValidity,
    ], $folders);

    freshcloud_mail_json(200, [
        'folders' => $payload,
        'count' => count($payload),
        'account_id' => $accountId,
        'user_id' => $userId,
        'timestamp' => gmdate('c'),
    ]);
} catch (\Throwable $e) {
    freshcloud_mail_error(500, 'list_folders_failed', $e->getMessage());
}
