import { describe, test, expect } from "bun:test";
import { toCSV } from "@/analytics/csv.js";

describe("toCSV", () => {
  test("emits header-only when there are no rows", () => {
    const out = toCSV([] as Array<{ a: string; b: string }>, ["a", "b"]);
    expect(out).toBe("a,b\n");
  });

  test("serializes simple rows with LF row separators", () => {
    const out = toCSV(
      [
        { a: 1, b: "hi" },
        { a: 2, b: "bye" },
      ],
      ["a", "b"] as const,
    );
    expect(out).toBe("a,b\n1,hi\n2,bye\n");
  });

  test("escapes commas by wrapping in quotes", () => {
    const out = toCSV([{ name: "hello, world" }], ["name"] as const);
    expect(out).toBe('name\n"hello, world"\n');
  });

  test("escapes quotes by doubling them", () => {
    const out = toCSV([{ name: 'he said "hi"' }], ["name"] as const);
    expect(out).toBe('name\n"he said ""hi"""\n');
  });

  test("escapes newlines by wrapping in quotes", () => {
    const out = toCSV([{ body: "line1\nline2" }], ["body"] as const);
    expect(out).toBe('body\n"line1\nline2"\n');
  });

  test("serializes null and undefined as empty fields", () => {
    const out = toCSV(
      [{ a: null as unknown as string, b: undefined as unknown as string, c: "x" }],
      ["a", "b", "c"] as const,
    );
    expect(out).toBe("a,b,c\n,,x\n");
  });

  test("respects column order (omits fields not listed)", () => {
    const out = toCSV([{ a: 1, b: 2, c: 3 }], ["c", "a"] as const);
    expect(out).toBe("c,a\n3,1\n");
  });
});
