<?php
declare(strict_types=1);

/**
 * GET /api/email/accounts
 * Returns all accounts for the current user + active account ID.
 * Per v0.1.0, multi-account is supported (operator decision 2026-07-23).
 */

header('Content-Type: application/json');

require_once __DIR__ . '/_bootstrap.php';

use FreshCloud\Mail\Identity\InMemoryIdentityProvider;

try {
    // v0.1.0: hardcoded user. v0.2.0: get from auth.
    $userId = 'user123';
    $identity = new InMemoryIdentityProvider();
    $accounts = $identity->getAllAccounts($userId);
    $activeAccountId = $identity->getActiveAccountId($userId);

    $response = [
        'accounts' => [],
        'active_account_id' => $activeAccountId,
    ];

    foreach ($accounts as $account) {
        // TODO v0.2.0: wire to mail-engine-cache for unread_count
        $unreadCount = 0;

        $response['accounts'][] = [
            'id' => $account['id'],
            'email' => $account['email'],
            'display_name' => $account['name'],
            'provider' => 'imap',
            'unread_count' => $unreadCount,
            'active' => ($account['id'] === $activeAccountId),
        ];
    }

    echo json_encode($response, JSON_PRETTY_PRINT);
} catch (\Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
