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

export type DebtorType = "individual" | "company";

export type Debtor = {
  id: number;
  type: DebtorType;
  full_name: string;
  national_id?: string | null;
  tax_id?: string | null;
  phone?: string | null;
  email?: string | null;
  address?: string | null;
  city?: string | null;
  country?: string | null;
  metadata?: any | null;
  created_at: string;
};

export type DebtorCreate = Omit<Debtor, "id" | "created_at">;

export async function listDebtors(params?: { q?: string; country?: string }): Promise<Debtor[]> {
  const sp = new URLSearchParams();
  if (params?.q) sp.set("q", params.q);
  if (params?.country) sp.set("country", params.country);
  const url = sp.toString() ? `/debtors/?${sp.toString()}` : "/debtors/";
  return api.request<Debtor[]>(url, { method: "GET" });
}

export async function createDebtor(payload: DebtorCreate): Promise<Debtor> {
  return api.request<Debtor>("/debtors/", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

// ✅ AJOUTS
export async function updateDebtor(
  id: number,
  payload: Partial<DebtorCreate>
): Promise<Debtor> {
  return api.request<Debtor>(`/debtors/${id}/`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}

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