import { formatAgorotPlain } from '@/lib/money';
import type { EarningsRow } from './types.js';

const BOM = '\uFEFF';

function escapeCsvCell(value: string | number): string {
  const str = String(value);
  if (/[",\n\r]/.test(str)) {
    return `"${str.replace(/"/g, '""')}"`;
  }
  return str;
}

const HEADERS = [
  'vendor',
  'month',
  'purchases',
  'gross_agorot',
  'vendor_agorot',
  'platform_fee_agorot',
  'refunded_agorot',
] as const;

export function earningsRowsToCsv(rows: EarningsRow[]): string {
  const headerLine = HEADERS.join(',');
  const lines = rows.map((r) =>
    [
      r.vendorBusinessName,
      r.monthYearMonth,
      r.purchaseCount,
      formatAgorotPlain(r.grossAgorot),
      formatAgorotPlain(r.vendorAmountAgorot),
      formatAgorotPlain(r.platformFeeAgorot),
      formatAgorotPlain(r.refundedAgorot),
    ]
      .map(escapeCsvCell)
      .join(','),
  );
  return BOM + [headerLine, ...lines].join('\n');
}
