export interface CrmExportRow {
  pledge_reference: string
  donor_name: string
  donor_email: string
  donor_phone: string
  amount_gbp: string
  payment_method: string
  status: string
  event_name: string
  source_label: string
  volunteer_name: string
  table_name: string
  gift_aid: string
  pledged_at: string
  paid_at: string
  days_to_collect: string
}

export function formatCrmExportCsv(rows: CrmExportRow[]): string {
  if (rows.length === 0) return ''
  const headers = Object.keys(rows[0])
  const lines = [
    headers.join(','),
    ...rows.map((row) =>
      headers
        .map((h) => {
          const val = (row as unknown as Record<string, string>)[h] || ''
          return val.includes(',') || val.includes('"') ? `"${val.replace(/"/g, '""')}"` : val
        })
        .join(',')
    ),
  ]
  return lines.join('\n')
}

export function formatWebhookPayload(event: string, data: Record<string, unknown>) {
  return {
    event,
    timestamp: new Date().toISOString(),
    data,
  }
}
