import type { EffectiveRemovalState, RemovalStatusByDeal } from "./types";

export function deriveEffectiveRemovalState(row: {
  type: string;
  status: string;
}): EffectiveRemovalState {
  if (row.status === "pending") {
    return row.type === "re_addition" ? "pending_re_addition" : "pending_removal";
  }
  if (row.type === "removal" && row.status === "approved") return "removed";
  if (row.type === "re_addition" && row.status === "declined") return "removed";
  return "none";
}

// Rows must be ordered by requestedAt DESC so the first row per deal is the most recent.
export function computeRemovalStatusByDeal(
  rows: { hubspotDealId: string; type: string; status: string }[],
): RemovalStatusByDeal {
  const result: RemovalStatusByDeal = {};
  const seen = new Set<string>();

  for (const row of rows) {
    if (seen.has(row.hubspotDealId)) continue;
    seen.add(row.hubspotDealId);

    const state = deriveEffectiveRemovalState(row);
    if (state !== "none") result[row.hubspotDealId] = state;
  }

  return result;
}
