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

export type CollectionEmailAttachment = {
  id: number;
  filename: string;
  content_type: string;
  size: number;
  file_url: string | null;
};

export type CollectionEmailStatus =
  | "draft"
  | "queued"
  | "sent"
  | "failed"
  | "received"
  | string;

export type CollectionEmailSource = "acx" | "outlook" | "other" | string;

export type CollectionEmail = {
  id: number;
  tenant?: number;
  case: number;
  action: number | null;

  direction: "outbound" | "inbound" | string;
  source: CollectionEmailSource;

  status?: CollectionEmailStatus;
  provider?: string;
  provider_message_id?: string;
  error_message?: string;

  from_address: string;
  to: string[] | null;
  cc: string[] | null;
  bcc: string[] | null;

  subject: string;
  sent_at: string | null;
  message_id: string;

  raw_eml_url: string | null;

  body_text: string;
  body_html: string;

  notes: string;

  attachments: CollectionEmailAttachment[];

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

export async function listCollectionEmails(params: {
  caseId?: number;
  actionId?: number;
}): Promise<CollectionEmail[]> {
  const qp: string[] = [];
  if (params.caseId) qp.push(`case=${encodeURIComponent(String(params.caseId))}`);
  if (params.actionId) qp.push(`action=${encodeURIComponent(String(params.actionId))}`);
  const url = `/collection-emails/${qp.length ? `?${qp.join("&")}` : ""}`;

  const res = await api.request<any>(url, { method: "GET" });
  // Supporte soit un tableau direct, soit une pagination DRF { results: [...] }.
  if (Array.isArray(res)) return res as CollectionEmail[];
  if (res && Array.isArray(res.results)) return res.results as CollectionEmail[];
  return [];
}

export async function attachCollectionEmailEml(params: {
  caseId: number;
  emlFile: File;
  actionId?: number | null;
  notes?: string;
  direction?: "outbound" | "inbound" | string;
  source?: CollectionEmailSource;
}): Promise<CollectionEmail & { timeline_action_id: number }> {
  const fd = new FormData();
  fd.append("case", String(params.caseId));
  if (params.actionId) fd.append("action", String(params.actionId));
  fd.append("file", params.emlFile);
  if (params.notes) fd.append("notes", params.notes);
  if (params.direction) fd.append("direction", params.direction);
  if (params.source) fd.append("source", params.source);

  return api.request<any>("/collection-emails/attach/", {
    method: "POST",
    body: fd as any,
  });
}


export async function sendCollectionEmail(params: {
  caseId: number;
  to: string; // accepte "a@x.com,b@y.com" ou JSON list côté backend
  cc?: string;
  bcc?: string;
  subject?: string;
  body_text?: string;
  body_html?: string;
  from_address?: string;
  notes?: string;
  actionId?: number | null;
  attachments?: File[];
}): Promise<CollectionEmail & { timeline_action_id: number }> {
  const files = params.attachments || [];

  // ✅ Si pas de pièces jointes, on envoie en JSON (plus simple et évite les soucis de parsers/Content-Type).
  if (files.length === 0) {
    const payload: any = {
      case: params.caseId,
      to: params.to,
      cc: params.cc,
      bcc: params.bcc,
      subject: params.subject,
      body_text: params.body_text,
      body_html: params.body_html,
      from_address: params.from_address,
      notes: params.notes,
      action: params.actionId ?? undefined,
    };

    // Nettoyage des champs vides / undefined
    Object.keys(payload).forEach((k) => {
      if (payload[k] === undefined || payload[k] === null || payload[k] === "") delete payload[k];
    });

    return api.request<any>("/collection-emails/send/", {
      method: "POST",
      body: JSON.stringify(payload),
    });
  }

  // ✅ Si PJ, on passe en multipart/form-data.
  const fd = new FormData();
  fd.append("case", String(params.caseId));
  fd.append("to", params.to);
  if (params.cc) fd.append("cc", params.cc);
  if (params.bcc) fd.append("bcc", params.bcc);
  if (params.subject) fd.append("subject", params.subject);
  if (params.body_text) fd.append("body_text", params.body_text);
  if (params.body_html) fd.append("body_html", params.body_html);
  if (params.from_address) fd.append("from_address", params.from_address);
  if (params.notes) fd.append("notes", params.notes);
  if (params.actionId) fd.append("action", String(params.actionId));

  for (const f of files) {
    fd.append("attachments", f);
  }

  return api.request<any>("/collection-emails/send/", {
    method: "POST",
    body: fd as any,
  });
}
