<?php
/**
 * FreshCloud Mail — list drafts for a user
 * GET /api/email/drafts?user_id=...&account_id=...
 *
 * Returns: 200 OK with array of draft summaries
 */

declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

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

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

$pb = freshcloud_mail_pb();

try {
    $response = $pb->collection('email_drafts')->getList(1, 50, [
        'filter' => sprintf('user_id="%s" && account_id="%s"', $userId, $accountId),
    ]);

    $items = $response['items'] ?? [];
    $drafts = array_map(fn($d) => [
        'id' => $d['id'] ?? null,
        'subject' => $d['subject'] ?? '(no subject)',
        'to' => json_decode($d['to'] ?? '[]', true) ?: [],
        'mode' => $d['mode'] ?? 'new',
        'status' => $d['status'] ?? 'draft',
        'updated_at' => $d['updated_at'] ?? $d['created_at'] ?? null,
    ], $items);

    freshcloud_mail_json(200, [
        'drafts' => $drafts,
        'count' => count($drafts),
        'user_id' => $userId,
        'account_id' => $accountId,
        'timestamp' => gmdate('c'),
    ]);
} catch (\Throwable $e) {
    // NullPb returns empty list, so this is fine
    freshcloud_mail_json(200, [
        'drafts' => [],
        'count' => 0,
        'user_id' => $userId,
        'account_id' => $accountId,
        'note' => 'In-memory PB — drafts not persisted',
        'timestamp' => gmdate('c'),
    ]);
}
