import { describe, expect, it } from "vitest";
import * as XLSX from "xlsx";
import { parseAssociationDirectoryWorkbook, resolveAssociationDirectoryImportRows } from "./associationDirectory";

function createWorkbookBuffer(rows: unknown[][]) {
  const worksheet = XLSX.utils.aoa_to_sheet(rows);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Associations");
  return XLSX.write(workbook, { type: "buffer", bookType: "xlsx" });
}

describe("association directory import parser", () => {
  it("parses valid workbook rows", () => {
    const buffer = createWorkbookBuffer([
      ["Nom association", "Email officiel", "Ville"],
      ["Association A", "asso-a@example.com", "Kourou"],
      ["Association B", "asso-b@example.com", "Sinnamary"],
    ]);

    const result = parseAssociationDirectoryWorkbook(buffer, "bordereau.xlsx");

    expect(result.totalRows).toBe(2);
    expect(result.validRows).toBe(2);
    expect(result.missingEmailRows).toBe(0);
    expect(result.duplicateEmailRows).toBe(0);
  });

  it("flags rows without email", () => {
    const buffer = createWorkbookBuffer([
      ["Nom association", "Email officiel", "Ville"],
      ["Association A", "", "Kourou"],
    ]);

    const result = parseAssociationDirectoryWorkbook(buffer, "bordereau.xlsx");

    expect(result.totalRows).toBe(1);
    expect(result.validRows).toBe(0);
    expect(result.missingEmailRows).toBe(1);
  });

  it("flags duplicate emails in the same workbook", () => {
    const buffer = createWorkbookBuffer([
      ["Nom association", "Email officiel", "Ville"],
      ["Association A", "same@example.com", "Kourou"],
      ["Association B", "same@example.com", "Macouria"],
    ]);

    const result = parseAssociationDirectoryWorkbook(buffer, "bordereau.xlsx");

    expect(result.validRows).toBe(0);
    expect(result.duplicateEmailRows).toBe(2);
    expect(result.duplicateGroups).toHaveLength(1);
    expect(result.duplicateGroups[0]?.options).toHaveLength(2);
  });

  it("can resolve one row per duplicate email group", () => {
    const buffer = createWorkbookBuffer([
      ["Nom association", "Email officiel", "Ville"],
      ["Association A", "same@example.com", "Kourou"],
      ["Association B", "same@example.com", "Macouria"],
      ["Association C", "", "Sinnamary"],
    ]);

    const result = parseAssociationDirectoryWorkbook(buffer, "bordereau.xlsx");
    const resolvedRows = resolveAssociationDirectoryImportRows(result, {
      "same@example.com": 2,
    });

    expect(resolvedRows).toHaveLength(2);
    expect(resolvedRows.some(row => row.nomAssociation === "Association A")).toBe(true);
    expect(resolvedRows.some(row => row.nomAssociation === "Association C")).toBe(true);
  });
});
