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

export type CreditorType = "company" | "individual"

export type Creditor = {
  id: number
  name: string
  code?: string | null
  type: CreditorType
  email?: string | null
  phone?: string | null
  country?: string | null
  city?: string | null
  address?: string | null
  tax_id?: string | null
  is_active: boolean
  notes?: string
  created_by?: number | null
  created_at: string
}

export type CreditorCreate = {
  name: string
  code?: string | null
  type?: CreditorType
  email?: string | null
  phone?: string | null
  country?: string | null
  city?: string | null
  address?: string | null
  tax_id?: string | null
  is_active?: boolean
  notes?: string
}

export type CreditorUpdate = Partial<CreditorCreate>

export function listCreditors(params?: { is_active?: boolean }): Promise<Creditor[]> {
  const qs = new URLSearchParams()
  if (params?.is_active != null) qs.set("is_active", String(params.is_active))
  const q = qs.toString()
  return api.request(`/creditors/${q ? `?${q}` : ""}`, { method: "GET" })
}

export function createCreditor(payload: CreditorCreate): Promise<Creditor> {
  return api.request("/creditors/", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}

export function updateCreditor(id: number, payload: CreditorUpdate): Promise<Creditor> {
  return api.request(`/creditors/${id}/`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}

export function deleteCreditor(id: number): Promise<void> {
  return api.request(`/creditors/${id}/`, { method: "DELETE" })
}
