<?php
/**
 * External Archival Journal Allowlist API for the mail VM
 *
 * Read-only endpoint that returns the list of mailbox addresses with Bichon
 * email archival currently enabled. The mail-VM Haraka journal plugin polls
 * this list to decide which recipients' mail to push (journal) into Bichon.
 *
 * Push/journaling model: WHP no longer pulls mail from mailboxes over IMAP.
 * Instead the mail VM pushes copies of mail to Bichon for the addresses in
 * this allowlist.
 *
 * Security:
 *   - Auth: standard external API key (X-Api-Key / X-Api-Secret) via api_auth.php
 *   - Permission: 'archival_journal' (grant this scope only to the mail-VM key)
 *   - Returns NO secrets — email addresses only.
 *
 * Request: GET /api/external/archival-journal.php
 *
 * Response:
 *   {
 *     "status": "success",
 *     "message": "OK",
 *     "data": {
 *       "generated_at": "2026-06-07T12:00:00+00:00",
 *       "addresses": ["alice@example.com", "bob@example.com"]
 *     }
 *   }
 *
 * On error returns the api_auth.php standard error envelope with an
 * appropriate HTTP status code.
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key, X-API-Secret, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once(__DIR__ . '/../../libs/api_auth.php');
require_once(__DIR__ . '/../../libs/mysqlmgmt.php');

try {
    // Standard external-API auth; mail-VM key must carry the 'archival_journal' scope.
    $authData = api_authenticate('archival_journal');

    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        api_response(false, null, 'Method not allowed. Use GET.', 405);
    }

    $MySQLMgmt = new mysqlmgmt();
    $db = $MySQLMgmt->getMySQLConnection();
    if (!$db) {
        api_response(false, null, 'Database connection failed', 500);
    }

    $stmt = $db->prepare("
        SELECT email_address
        FROM whp.email_accounts
        WHERE archival_enabled = 1
          AND email_address IS NOT NULL
          AND email_address <> ''
        ORDER BY email_address
    ");
    $stmt->execute();
    $addresses = $stmt->fetchAll(PDO::FETCH_COLUMN);

    api_response(true, [
        'generated_at' => gmdate('c'),
        'addresses'    => $addresses,
    ], 'OK', 200);

} catch (Exception $e) {
    error_log('External archival-journal API error: ' . $e->getMessage());
    api_response(false, null, 'Internal server error', 500);
}
