import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiFetch } from "./client";
import { getToken } from "@/auth/AuthProvider";
import type { ProcessingEntry, GdprAccessResult, ErasureResult } from "@/types/api";

const BASE = "/v1/admin/compliance";

// ─── Entries CRUD ──────────────────────────────────────────────────────────────

export function useListEntries() {
  return useQuery({
    queryKey: ["compliance", "entries"],
    queryFn: () => apiFetch<{ data: ProcessingEntry[] }>(`${BASE}/entries`).then((r) => r.data),
  });
}

export function useGetEntry(id: string) {
  return useQuery({
    queryKey: ["compliance", "entries", id],
    queryFn: () => apiFetch<ProcessingEntry>(`${BASE}/entries/${id}`),
    enabled: !!id,
  });
}

export function useCreateEntry() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (body: Omit<ProcessingEntry, "id" | "risk_level" | "ai_act_answers" | "is_active" | "created_at" | "updated_at">) =>
      apiFetch<ProcessingEntry>(`${BASE}/entries`, { method: "POST", body: JSON.stringify(body) }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["compliance", "entries"] }),
  });
}

export function useUpdateEntry() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, ...body }: Partial<ProcessingEntry> & { id: string }) =>
      apiFetch<ProcessingEntry>(`${BASE}/entries/${id}`, { method: "PUT", body: JSON.stringify(body) }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["compliance", "entries"] }),
  });
}

export function useDeleteEntry() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiFetch<void>(`${BASE}/entries/${id}`, { method: "DELETE" }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["compliance", "entries"] }),
  });
}

// ─── AI Act classification ─────────────────────────────────────────────────────

export function useClassifyEntry() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, answers }: { id: string; answers: Record<string, boolean> }) =>
      apiFetch<ProcessingEntry>(`${BASE}/entries/${id}/classify`, {
        method: "POST",
        body: JSON.stringify({ answers }),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["compliance", "entries"] }),
  });
}

// ─── GDPR ──────────────────────────────────────────────────────────────────────

export function useGdprAccess(userId: string, enabled: boolean) {
  return useQuery({
    queryKey: ["compliance", "gdpr", "access", userId],
    queryFn: () => apiFetch<GdprAccessResult>(`${BASE}/gdpr/access/${encodeURIComponent(userId)}`),
    enabled: enabled && !!userId,
  });
}

export function useGdprErase() {
  return useMutation({
    mutationFn: ({ userId, reason }: { userId: string; reason: string }) =>
      apiFetch<ErasureResult>(`${BASE}/gdpr/erase/${encodeURIComponent(userId)}`, {
        method: "DELETE",
        body: JSON.stringify({ reason }),
      }),
  });
}

// ─── PDF / CSV download utility ────────────────────────────────────────────────

export async function downloadPdf(url: string, filename: string): Promise<void> {
  const token = getToken();
  const headers: Record<string, string> = {};
  if (token) headers["Authorization"] = `Bearer ${token}`;

  const res = await fetch(url, { headers });
  if (!res.ok) throw new Error(`Download failed: HTTP ${res.status}`);

  const blob = await res.blob();
  const objectUrl = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = objectUrl;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(objectUrl);
}
