import type { ParsedEventRow } from "@/lib/types";

export function mergeIncomingRows(rows: ParsedEventRow[]) {
  const byEvent = new Map<string, ParsedEventRow>();

  for (const row of rows) {
    const key = row.sent_email_name.trim();
    if (!key) continue;

    const existing = byEvent.get(key);
    if (!existing) {
      byEvent.set(key, row);
      continue;
    }

    // Within a single upload, prefer the latest encountered row for conflicting values.
    byEvent.set(key, {
      ...existing,
      primary_country_code: row.primary_country_code || existing.primary_country_code,
      approved_document_name: row.approved_document_name || existing.approved_document_name,
      brand: row.brand || existing.brand,
      last_open: row.last_open ?? existing.last_open,
      opened: row.opened,
      total_opens: row.total_opens,
      last_click: row.last_click ?? existing.last_click,
      clicked: row.clicked,
      total_clicks: row.total_clicks,
      sent_date: row.sent_date ?? existing.sent_date,
      source_row_number: row.source_row_number,
      source_sheet_name: row.source_sheet_name || existing.source_sheet_name,
    });
  }

  return [...byEvent.values()];
}
