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

/**
 * Collections / Recouvrement
 *
 * IMPORTANT:
 * On utilise le même client API que le reste du front (api.request),
 * afin d'envoyer les requêtes vers le backend (base URL) et éviter
 * de taper le serveur Next.js (/api/* -> 404 HTML).
 */

export type CollectionCasePriority = "low" | "medium" | "high" | string;
export type CollectionCaseStatus = "open" | "closed" | "in_progress" | "on_hold" | string;

export type CollectionCase = {
  id: number;
  tenant: number;
  reference: string;

  debtor?: number | null;
  debtor_ref?: string | null;
  portfolio?: number | null;

  currency?: string;
  amount_due?: string;
  amount_collected?: string;

  status?: CollectionCaseStatus;
  priority?: CollectionCasePriority;

  created_at?: string;
  updated_at?: string;
};

export type CollectionActionType =
  | "call"
  | "sms"
  | "email"
  | "outlook_proof"
  | "promise"
  | "payment"
  | "legal"
  | string;

export type CollectionActionOutcome = "reached" | "not_reached" | "no_answer" | "pending" | string;

export type CollectionAction = {
  id: number;
  tenant: number;
  case: number;

  action_type: CollectionActionType;
  outcome: CollectionActionOutcome;

  action_date: string;
  summary: string;
  details: string;

  next_action_type?: CollectionActionType | null;
  next_action_date?: string | null;

  created_by?: number | null;
  created_at?: string;

  // Certains backends renvoient aussi une structure JSON détaillée
  details_json?: any;
};

export type PaymentPromiseStatus = "pending" | "fulfilled" | "broken" | "cancelled" | string;

export type PaymentPromise = {
  id: number;
  tenant: number;
  case: number;

  amount: string;
  currency?: string;

  promised_date: string;
  status: PaymentPromiseStatus;

  notes?: string;
  created_by?: number | null;
  created_at?: string;

  meta?: any;
};

export type PaymentMethod = "cash" | "bank_transfer" | "mobile_money" | "cheque" | "other" | string;

export type PaymentReceivedBy = "acx" | "customer_direct" | "agent" | string;

export type Payment = {
  id: number;
  tenant: number;
  case: number;

  amount: string;
  currency?: string;

  method: PaymentMethod;
  received_by?: PaymentReceivedBy;

  reference?: string;
  notes?: string;

  paid_at: string;

  created_by?: number | null;
  created_at?: string;

  meta?: any;
};

export type CollectionCaseTimeline = {
  case: CollectionCase;
  actions: CollectionAction[];
  promises: PaymentPromise[];
  payments: Payment[];
};

function normalizeListResponse<T>(res: any): T[] {
  if (Array.isArray(res)) return res as T[];
  if (res && Array.isArray(res.results)) return res.results as T[];
  return [];
}

function buildQuery(params: Record<string, any>): string {
  const qp: string[] = [];
  for (const [k, v] of Object.entries(params)) {
    if (v === undefined || v === null || v === "") continue;
    qp.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
  }
  return qp.length ? `?${qp.join("&")}` : "";
}

// -------------------- Collection cases --------------------

export async function listCollectionCases(params?: {
  q?: string;
  status?: string;
  priority?: string;
  ordering?: string;
  debtor?: number;
  portfolio?: number;
}): Promise<CollectionCase[]> {
  const qs = buildQuery({
    q: params?.q,
    status: params?.status,
    priority: params?.priority,
    ordering: params?.ordering,
    debtor: params?.debtor,
    portfolio: params?.portfolio,
  });

  // Trailing slash obligatoire dans beaucoup de setups Django/Next (rewrites/proxy)
  const res = await api.request<any>(`/collection-cases/${qs}`, { method: "GET" });
  return normalizeListResponse<CollectionCase>(res);
}

export async function createCollectionCase(payload: {
  reference: string;
  debtor?: number | null;
  portfolio?: number | null;
  currency?: string;
  amount_due?: string | number;
  priority?: CollectionCasePriority;
  meta?: any;
}): Promise<CollectionCase> {
  return api.request<CollectionCase>(`/collection-cases/`, {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export async function getCollectionCaseTimeline(caseId: number, limitActions: number = 50): Promise<CollectionCaseTimeline> {
  const url = `/collection-cases/${caseId}/timeline/?limit_actions=${encodeURIComponent(String(limitActions))}`;
  return api.request<CollectionCaseTimeline>(url, { method: "GET" });
}

// -------------------- Actions --------------------

export async function createCollectionAction(payload: {
  case: number;
  action_type: CollectionActionType;
  outcome?: CollectionActionOutcome;
  action_date?: string;
  summary?: string;
  details?: string;
  next_action_type?: CollectionActionType | null;
  next_action_date?: string | null;
  details_json?: any;
}): Promise<CollectionAction> {
  return api.request<CollectionAction>(`/collection-actions/`, {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

// -------------------- Promesses de paiement --------------------

export async function createPaymentPromise(payload: {
  case: number;
  amount: string | number;
  promised_date: string;
  notes?: string;
  meta?: any;
}): Promise<PaymentPromise> {
  return api.request<PaymentPromise>(`/payment-promises/`, {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

// -------------------- Paiements --------------------

export async function createPayment(payload: {
  case: number;
  amount: string | number;
  method: PaymentMethod;
  reference?: string;
  notes?: string;
  paid_at?: string;
  received_by?: PaymentReceivedBy;
  treasury_account?: number | null;
  meta?: any;
}): Promise<Payment> {
  return api.request<Payment>(`/payments/`, {
    method: "POST",
    body: JSON.stringify(payload),
  });
}
