/**
 * Pure parsing for Bulk tag assignment (ADR-0013). The client reads the uploaded
 * CSV/Excel into a 2D array of rows (header row first, via SheetJS) and this
 * turns it into the identifier column to match on — either `landlord_property_id`
 * or `uprn`, whichever header the file carries. Kept DB-free so it unit-tests and
 * runs in the browser before anything is sent to the server.
 */

/** Upper bound on rows per upload ("relatively small file", ADR-0013). */
export const MAX_BULK_TAG_ROWS = 10_000;

export type IdentifierKey = "landlord_property_id" | "uprn";

export type ParsedIdentifiers =
  | { ok: true; key: IdentifierKey; identifiers: string[] }
  | { ok: false; error: string };

type Cell = string | number | null | undefined;

/** Normalise a header cell: trimmed, lowercased, spaces/hyphens → underscores. */
function normaliseHeader(cell: Cell): string {
  return String(cell ?? "")
    .trim()
    .toLowerCase()
    .replace(/[\s-]+/g, "_");
}

export function parseTagIdentifierRows(rows: Cell[][]): ParsedIdentifiers {
  const [header, ...dataRows] = rows;
  const headers = (header ?? []).map(normaliseHeader);

  const keyIndex = headers.findIndex(
    (h) => h === "landlord_property_id" || h === "uprn",
  );
  if (keyIndex === -1) {
    return {
      ok: false,
      error:
        "The file needs a 'landlord_property_id' or 'uprn' column in the first row",
    };
  }
  const key = headers[keyIndex] as IdentifierKey;

  const seen = new Set<string>();
  for (const row of dataRows) {
    const value = String(row[keyIndex] ?? "").trim();
    if (value.length > 0) seen.add(value);
  }

  if (seen.size === 0) {
    return { ok: false, error: "The file has no rows to assign" };
  }
  if (seen.size > MAX_BULK_TAG_ROWS) {
    return {
      ok: false,
      error: `The file has more than ${MAX_BULK_TAG_ROWS} properties — split it into smaller files`,
    };
  }

  return { ok: true, key, identifiers: [...seen] };
}
