/**
 * Price checks (zero price / below cost / below minimum) look only at
 * lines the user added or changed (client 2026-11-05). A line sold
 * earlier and left untouched must not block a save just because the
 * minimum price was raised afterwards.
 *
 * A payload row counts as unchanged when it carries the id of a saved
 * row and every price-relevant field matches. Rows without an id are
 * new. If a category's payload has no ids at all (older clients), every
 * row is treated as changed — the safe default.
 * Special items have no id: a row is unchanged when a saved special
 * with the same name, date and price exists (each saved row used once).
 */

type Row = Record<string, unknown>;

export interface SavedLines {
  hotel_items: Row[];
  transport_items: Row[];
  activity_items: Row[];
  special_items: Row[];
}

const PRICE_FIELDS: Record<'hotel_items' | 'transport_items' | 'activity_items', string[]> = {
  hotel_items: ['hotel_id', 'subtotal'],
  transport_items: [
    'transport_service_id',
    'vehicle_type_id',
    'is_shared',
    'supplier_id',
    'date',
    'quantity',
    'unit_price',
    'subtotal',
  ],
  activity_items: [
    'activity_id',
    'ticket_id',
    'age_group',
    'date',
    'quantity',
    'unit_price',
    'subtotal',
  ],
};

const NUMERIC = new Set(['quantity', 'unit_price', 'subtotal', 'total_price']);

function norm(field: string, v: unknown): string {
  if (v === undefined || v === null || v === '') return '';
  if (NUMERIC.has(field)) return String(Number(v));
  if (field === 'date') {
    if (v instanceof Date) {
      const p = (n: number) => String(n).padStart(2, '0');
      return `${v.getFullYear()}-${p(v.getMonth() + 1)}-${p(v.getDate())}`;
    }
    return String(v).slice(0, 10);
  }
  return String(v);
}

function changed(fields: string[], next: Row, saved: Row): boolean {
  // A field the payload leaves out keeps its saved value.
  return fields.some((f) => f in next && norm(f, next[f]) !== norm(f, saved[f]));
}

function filterById(rows: unknown, saved: Row[], fields: string[]): unknown {
  if (!Array.isArray(rows)) return rows;
  const list = rows as Row[];
  if (!list.some((r) => r?.id)) return list; // no ids → all count as changed
  const byId = new Map(saved.map((s) => [String(s.id), s]));
  return list.filter((r) => {
    const s = r?.id ? byId.get(String(r.id)) : undefined;
    return !s || changed(fields, r, s);
  });
}

function filterSpecials(rows: unknown, saved: Row[]): unknown {
  if (!Array.isArray(rows)) return rows;
  const key = (r: Row) =>
    `${norm('service_name', r.service_name)}|${norm('date', r.date)}|${norm('total_price', r.total_price)}`;
  const pool = new Map<string, number>();
  for (const s of saved) pool.set(key(s), (pool.get(key(s)) ?? 0) + 1);
  return (rows as Row[]).filter((r) => {
    const k = key(r);
    const left = pool.get(k) ?? 0;
    if (left > 0) {
      pool.set(k, left - 1);
      return false;
    }
    return true;
  });
}

/** Same shape as the payload, keeping only new or changed line items. */
export function onlyNewOrChangedLines<T extends object>(dto: T, saved: SavedLines): T {
  const d = dto as unknown as Row;
  return {
    ...dto,
    hotel_items: filterById(d.hotel_items, saved.hotel_items, PRICE_FIELDS.hotel_items),
    transport_items: filterById(
      d.transport_items,
      saved.transport_items,
      PRICE_FIELDS.transport_items,
    ),
    activity_items: filterById(d.activity_items, saved.activity_items, PRICE_FIELDS.activity_items),
    special_items: filterSpecials(d.special_items, saved.special_items),
  } as T;
}
