export interface ExportableContact {
  name: string | null;
  email: string;
  phone: string | null;
  tags: string[];
  status: string;
  source: string;
  createdAt: Date;
  listMemberships: { list: { name: string } }[];
}

export const CONTACT_EXPORT_COLUMNS = {
  name: { label: "Nome", get: (c: ExportableContact) => c.name ?? "" },
  email: { label: "E-mail", get: (c: ExportableContact) => c.email },
  phone: { label: "Telefone", get: (c: ExportableContact) => c.phone ?? "" },
  tags: { label: "Tags", get: (c: ExportableContact) => c.tags.join(", ") },
  status: { label: "Status", get: (c: ExportableContact) => c.status },
  source: { label: "Origem", get: (c: ExportableContact) => c.source },
  createdAt: { label: "Data de Criação", get: (c: ExportableContact) => c.createdAt.toLocaleString("pt-BR") },
  lists: { label: "Listas", get: (c: ExportableContact) => c.listMemberships.map((m) => m.list.name).join(", ") },
} as const;

export type ContactExportColumn = keyof typeof CONTACT_EXPORT_COLUMNS;

export const ALL_CONTACT_EXPORT_COLUMNS = Object.keys(CONTACT_EXPORT_COLUMNS) as ContactExportColumn[];

function escapeCsvField(value: string): string {
  return `"${value.replace(/"/g, '""')}"`;
}

/** Mesmo padrão de CSV já usado em `build-email-history-csv.ts`: `;`-delimitado com BOM UTF-8. */
export function buildContactsExportCsv(contacts: ExportableContact[], columns: ContactExportColumn[]): string {
  const cols = columns.length > 0 ? columns : ALL_CONTACT_EXPORT_COLUMNS;
  const headers = cols.map((col) => CONTACT_EXPORT_COLUMNS[col].label);
  const rows = contacts.map((contact) => cols.map((col) => escapeCsvField(String(CONTACT_EXPORT_COLUMNS[col].get(contact)))));

  const body = [headers.join(";"), ...rows.map((row) => row.join(";"))].join("\n");
  return "﻿" + body;
}
