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

// PROJ-50: DSGVO-Löschersuchen für Mail-Inhalte (GoBD-Vorrang).
// Endpoints unter /api/admin/dsgvo. Zugriff: admin/superadmin/domain_admin (RW),
// auditor/domain_auditor (read-only).

export type DSGVOStatus = "open" | "partial" | "completed" | "failed";

export type DSGVOMailStatus = "rejected" | "deletable" | "deleted";

// Feldnamen 1:1 zu internal/storage/dsgvo_requests.go (DSGVOAffectedMail).
// Es gibt kein "status"-Feld im Backend — der Status wird aus
// deletable/deleted abgeleitet (siehe mailStatus() im Tab).
export interface DSGVOMailResult {
  mail_id: string;
  subject: string;
  date: string | null;
  retain_until: string | null;
  deletable: boolean;
  deleted: boolean;
  reason?: string;
}

// Feldnamen 1:1 zu internal/storage/dsgvo_requests.go (DSGVOResultSummary).
export interface DSGVOResultSummary {
  total_hits: number;
  rejected: number;
  deletable: number;
  deleted: number;
  truncated: boolean;
  mails: DSGVOMailResult[];
}

export interface DSGVORequest {
  id: number;
  tenant_id: number | null;
  requested_address: string;
  requested_by: string;
  created_at: string;
  status: DSGVOStatus;
  result_summary: DSGVOResultSummary | null;
}

export interface CreateDSGVORequestInput {
  address: string;
  date_from?: string;
  date_to?: string;
}

export async function getDSGVORequests(): Promise<DSGVORequest[]> {
  const data = await request<{ requests: DSGVORequest[] | null }>("/api/admin/dsgvo");
  return data.requests ?? [];
}

export async function getDSGVORequest(id: number): Promise<DSGVORequest> {
  return request<DSGVORequest>(`/api/admin/dsgvo/${id}`);
}

export async function createDSGVORequest(
  input: CreateDSGVORequestInput
): Promise<DSGVORequest> {
  return request<DSGVORequest>("/api/admin/dsgvo", {
    method: "POST",
    body: JSON.stringify(input),
  });
}

export async function deleteDSGVODeletableMails(
  id: number
): Promise<DSGVORequest> {
  return request<DSGVORequest>(`/api/admin/dsgvo/${id}/delete`, {
    method: "POST",
  });
}

export async function exportDSGVORequestPDF(
  id: number
): Promise<{ blob: Blob; filename: string }> {
  const res = await fetch(`${API_BASE}/api/admin/dsgvo/${id}/export`, {
    credentials: "include",
  });
  if (!res.ok) throw new Error("PDF-Export fehlgeschlagen");
  const blob = await res.blob();
  const cd = res.headers.get("Content-Disposition") || "";
  const filename =
    cd.match(/filename="([^"]+)"/)?.[1] || `dsgvo-antrag-${id}.pdf`;
  return { blob, filename };
}
