import { describe, expect, it } from "vitest";
import { parseTagIdentifierRows, MAX_BULK_TAG_ROWS } from "./bulkAssign";

describe("parseTagIdentifierRows", () => {
  it("extracts landlord property ids from a landlord_property_id column", () => {
    const rows = [["landlord_property_id"], ["ABC-001"], ["ABC-002"]];
    expect(parseTagIdentifierRows(rows)).toEqual({
      ok: true,
      key: "landlord_property_id",
      identifiers: ["ABC-001", "ABC-002"],
    });
  });

  it("detects a UPRN column (header normalised case-insensitively)", () => {
    const rows = [["UPRN"], [100023336956], [100023336957]];
    expect(parseTagIdentifierRows(rows)).toEqual({
      ok: true,
      key: "uprn",
      identifiers: ["100023336956", "100023336957"],
    });
  });

  it("normalises a spaced/cased header and trims + dedupes + drops blank ids", () => {
    const rows = [
      ["Landlord Property ID"],
      ["  ABC-001 "],
      ["ABC-001"],
      [""],
      ["ABC-002"],
    ];
    expect(parseTagIdentifierRows(rows)).toEqual({
      ok: true,
      key: "landlord_property_id",
      identifiers: ["ABC-001", "ABC-002"],
    });
  });

  it("errors when neither identifier column is present", () => {
    const rows = [["address", "postcode"], ["12 Oak St", "SW1"]];
    expect(parseTagIdentifierRows(rows)).toEqual({
      ok: false,
      error:
        "The file needs a 'landlord_property_id' or 'uprn' column in the first row",
    });
  });

  it("errors on an empty file (no data rows)", () => {
    expect(parseTagIdentifierRows([["uprn"]])).toEqual({
      ok: false,
      error: "The file has no rows to assign",
    });
  });

  it("errors when the file exceeds the row cap", () => {
    const rows: (string | number)[][] = [["uprn"]];
    for (let i = 0; i < MAX_BULK_TAG_ROWS + 1; i++) rows.push([`1000${i}`]);
    const result = parseTagIdentifierRows(rows);
    expect(result.ok).toBe(false);
    expect(result.ok === false && result.error).toContain(
      String(MAX_BULK_TAG_ROWS),
    );
  });
});
