import { getCloudConfig, getDeviceId, getDeviceName } from './config.js';
import { enqueueFailedQuarantineSync } from './sync-queue.js';
import { redactCredentials } from '../defence/credential-leak/index.js';
/**
 * Fire-and-forget: sends quarantined content to ShieldCortex cloud.
 * Never blocks, never throws. Failed requests are logged and queued for retry.
 *
 * IMPORTANT: Content is redacted before transmission — credentials and secrets
 * are replaced with [REDACTED-{type}] placeholders to prevent PII/secret leakage.
 */
export function syncQuarantineToCloud(entry) {
    const config = getCloudConfig();
    if (!config.cloudEnabled || !config.cloudApiKey)
        return;
    const payload = {
        ...entry,
        // Redact credentials/secrets before sending to cloud
        original_content: redactCredentials(entry.original_content),
        original_title: entry.original_title ? redactCredentials(entry.original_title) : entry.original_title,
        device_id: getDeviceId(),
        device_name: getDeviceName(),
        timestamp: new Date().toISOString(),
    };
    const url = `${config.cloudBaseUrl}/v1/quarantine/ingest`;
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 10_000);
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${config.cloudApiKey}`,
        },
        body: JSON.stringify(payload),
        signal: controller.signal,
    })
        .then((res) => {
        if (!res?.ok) {
            console.error(`[shieldcortex] Quarantine sync failed: HTTP ${res.status}`);
            try {
                enqueueFailedQuarantineSync(payload);
            }
            catch { /* non-critical */ }
        }
    })
        .catch((e) => {
        console.error('[shieldcortex] Quarantine sync failed:', e instanceof Error ? e.message : String(e));
        try {
            enqueueFailedQuarantineSync(payload);
        }
        catch { /* non-critical */ }
    })
        .finally(() => clearTimeout(timeout));
}
