<?php
/**
 * FreshCloud Mail — list messages in a folder
 * GET /api/email/messages?account_id=...&folder=INBOX&limit=50&offset=0
 *
 * Returns: 200 OK with array of MessageInfo
 */

declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

$accountId = $_GET['account_id'] ?? null;
$userId = $_GET['user_id'] ?? 'admin@freshvibeapps.local';
$folder = $_GET['folder'] ?? 'INBOX';
$limit = (int) ($_GET['limit'] ?? 50);
$offset = (int) ($_GET['offset'] ?? 0);

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

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

$imapCommands = new \FreshCloud\Mail\ImapCommands\InMemoryImapCommands($pb, $logger);

try {
    $messages = $imapCommands->listMessages($userId, $accountId, $folder, $limit, $offset);

    $payload = array_map(fn($m) => [
        'uid' => $m->uid,
        'folder' => $m->folder,
        'subject' => $m->subject,
        'from_address' => $m->fromAddress,
        'from_name' => $m->fromName,
        'date' => $m->date?->format('c'),
        'size' => $m->size,
        'flags' => $m->flags,
        'has_attachments' => $m->hasAttachments,
        'message_id' => $m->messageId,
        'preview' => $m->preview,
    ], $messages);

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