import { API_BASE, request } from "./core";

// ── Types ────────────────────────────────────────────────────────────────────

export interface ReconciliationPoint {
  date: string; // "2026-06-27"
  archived_count: number | null;
  expected_count: number | null;
  delta: number | null;
  missing: boolean; // true = kein Report-Datensatz (Cron nicht gelaufen) ≠ archived_count:0
}

export interface ReconciliationSource {
  source_type: string; // "smtp" | "imap" | "pop3" | "import"
  source_id: number | null;
  source_key: string; // "smtp" | "import" | "imap:<id>" | "pop3:<id>"
  tenant_id: number | null;
  points: ReconciliationPoint[];
  avg_7d: number | null;
  enough_data: boolean;
  alert: boolean;
}

export interface ReconciliationResponse {
  days: number;
  threshold_pct: number;
  sources: ReconciliationSource[];
}

// ── API ──────────────────────────────────────────────────────────────────────

export async function getReconciliation(days = 7): Promise<ReconciliationResponse> {
  return request<ReconciliationResponse>(`/api/admin/reconciliation?days=${days}`);
}

/** Lädt den Reconciliation-Report als CSV-Datei herunter. */
export async function exportReconciliationCSV(
  days = 30
): Promise<{ blob: Blob; filename: string }> {
  const res = await fetch(
    `${API_BASE}/api/admin/reconciliation/export.csv?days=${days}`,
    { credentials: "include" }
  );
  if (!res.ok) throw new Error(`Export fehlgeschlagen: ${res.status}`);
  const disposition = res.headers.get("Content-Disposition") || "";
  const match = disposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
  const filename = match
    ? match[1].replace(/['"]/g, "")
    : `reconciliation-${days}d.csv`;
  return { blob: await res.blob(), filename };
}
