import { api } from "@/src/lib/api/client";

export type CaseStatus = "open" | "in_progress" | "on_hold" | "closed";
export type CasePriority = "low" | "medium" | "high" | "urgent";

export type CasePortfolio = { id: number; name: string; description?: string | null; is_active: boolean; created_at: string } | null;

export type CaseDebtor = {
  id: number;
  type: "individual" | "company";
  full_name: string;
  phone?: string | null;
  email?: string | null;
  city?: string | null;
  country?: string | null;
};

export type Case = {
  id: number;
  reference: string;
  title: string;
  status: CaseStatus;
  priority: CasePriority;

  currency?: string | null;
  original_amount: string; // DRF renvoie string
  balance_amount: string;

  due_date?: string | null;
  opened_at: string;
  closed_at?: string | null;

  portfolio: CasePortfolio;
  customer?: number | null;         // client id
  customer_name?: string | null;    // client name
  creditor?: number | null;         // créancier réel (null = même que le client)
  creditor_name?: string | null;    // nom du créancier réel (ou du client si pas de créancier distinct)
  debtor: CaseDebtor;
  assigned_to_id?: number | null;
  assigned_to_username?: string | null;

  metadata?: any | null;
};

export type CaseCreate = {
  title: string;
  status?: CaseStatus;
  priority?: CasePriority;
  currency?: string | null;
  original_amount?: string | number;
  balance_amount?: string | number;
  due_date?: string | null;

  customer_id?: number;
  portfolio_id?: number | null;
  debtor_id: number;
  creditor_id?: number | null;
  assigned_to_id?: number | null;
  notify_customer?: boolean;
  notify_creditor?: boolean;
  notify_debtor?: boolean;
  metadata?: any | null;
};

export type CaseNote = {
  id: number;
  case: number;
  author_username?: string | null;
  body: string;
  created_at: string;
  updated_at?: string | null;
};

export type CaseDocument = {
  id: number;
  case: number;
  title: string;
  doc_type: "contract" | "invoice" | "letter" | "id" | "other";
  file: string;
  file_url?: string | null;
  uploaded_by_username?: string | null;
  created_at: string;
};

export async function listCases(params?: {
  status?: CaseStatus | "";
  assigned_to?: string | number | "";
  q?: string;
  portfolio?: number | string;
  country?: string;
}): Promise<Case[]> {
  const sp = new URLSearchParams();
  if (params?.status) sp.set("status", String(params.status));
  if (params?.assigned_to) sp.set("assigned_to", String(params.assigned_to));
  if (params?.q) sp.set("q", params.q);
  if (params?.portfolio) sp.set("portfolio", String(params.portfolio));
  if (params?.country) sp.set("country", params.country);

  const url = sp.toString() ? `/cases/?${sp.toString()}` : "/cases/";
  return api.request<Case[]>(url, { method: "GET" });
}

export async function createCase(payload: CaseCreate): Promise<Case> {
  return api.request<Case>("/cases/", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export async function fetchCase(id: number): Promise<Case> {
  return api.request<Case>(`/cases/${id}/`, { method: "GET" });
}

export async function updateCase(id: number, payload: Partial<CaseCreate>): Promise<Case> {
  return api.request<Case>(`/cases/${id}/`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}

export async function deleteCase(id: number): Promise<void> {
  await api.request(`/cases/${id}/`, { method: "DELETE" });
}

export async function listCaseNotes(caseId: number): Promise<CaseNote[]> {
  return api.request<CaseNote[]>(`/cases/${caseId}/notes/`, { method: "GET" });
}

export async function createCaseNote(caseId: number, body: string): Promise<CaseNote> {
  return api.request<CaseNote>(`/cases/${caseId}/notes/`, {
    method: "POST",
    body: JSON.stringify({ body }),
  });
}

export async function patchCaseNote(caseId: number, noteId: number, body: string): Promise<CaseNote> {
  return api.request<CaseNote>(`/cases/${caseId}/notes/${noteId}/`, {
    method: "PATCH",
    body: JSON.stringify({ body }),
  });
}

export async function deleteCaseNote(caseId: number, noteId: number): Promise<void> {
  await api.request(`/cases/${caseId}/notes/${noteId}/`, { method: "DELETE" });
}

export async function listCaseDocuments(caseId: number): Promise<CaseDocument[]> {
  return api.request<CaseDocument[]>(`/cases/${caseId}/documents/`, { method: "GET" });
}


// src/lib/api/cases.ts
import { tokenStorage } from "@/src/lib/api/storage"

export async function uploadCaseDocument(
  caseId: number,
  payload: { title: string; doc_type: string; file: File }
) {
  const BASE = process.env.NEXT_PUBLIC_API_BASE_URL || ""
  const base = BASE.replace(/\/+$/, "")
  const url = `${base}/cases/${caseId}/documents/`

  const fd = new FormData()
  fd.append("title", payload.title)
  fd.append("doc_type", payload.doc_type)
  fd.append("file", payload.file)

  const access = tokenStorage.getAccess()

  const res = await fetch(url, {
    method: "POST",
    body: fd,
    headers: access ? { Authorization: `Bearer ${access}` } : undefined,
  })

  if (!res.ok) {
    let msg = "Upload échoué."
    try {
      const j = await res.json()
      msg = j?.detail || j?.message || msg
    } catch {}
    throw new Error(msg)
  }

  return res.json()
}
