import type { TFunction } from "i18next";
import { describe, expect, test } from "vitest";
import type { FeedbackRecordData } from "@/modules/hub/types";
import { FIELD_TYPE_ICON_MAP } from "./field-type-icons";
import {
  formatFieldType,
  formatFieldTypeLabel,
  formatSourceType,
  getEmbeddedDataEntries,
  getReadOnlyMetadataEntries,
  getTaxonomyAssignmentDisplay,
  getValueFieldByType,
  isPresetSourceType,
  mapRecordToValues,
  parseNumberValue,
  resolveFeedbackDisplayText,
  toISOOrUndefined,
  toLocalDateTimeInput,
} from "./utils";

// Returns the key so the assertions can read which translation key the formatter picked.
const t = ((key: string) => key) as TFunction;

const makeRecord = (overrides: Partial<FeedbackRecordData> = {}): FeedbackRecordData => ({
  id: "rec-1",
  tenant_id: "tenant-1",
  submission_id: "sub-1",
  collected_at: "2026-03-15T12:00:00.000Z",
  created_at: "2026-03-15T12:00:00.000Z",
  updated_at: "2026-03-15T12:00:00.000Z",
  source_type: "survey",
  field_id: "f1",
  field_type: "text",
  ...overrides,
});

describe("getTaxonomyAssignmentDisplay", () => {
  test("shows the full ordered visible path", () => {
    expect(
      getTaxonomyAssignmentDisplay({
        status: "classified",
        run_id: "run-1",
        path: [
          { id: "topic", label: "Product", level: 1, node_type: "branch" },
          { id: "subtopic", label: "Login", level: 2, node_type: "leaf" },
        ],
      })
    ).toEqual({ path: "Product › Login", status: "classified" });
  });

  test.each(["no_active_taxonomy", "unclassified"] as const)("uses the distinct %s state", (status) => {
    expect(getTaxonomyAssignmentDisplay({ status, run_id: null, path: [] })).toEqual({ path: null, status });
  });

  test("lookup failure is unavailable, not unclassified", () => {
    expect(getTaxonomyAssignmentDisplay(null)).toEqual({ path: null, status: "unavailable" });
  });
});

describe("getValueFieldByType", () => {
  test.each([
    ["boolean", "value_boolean"],
    ["date", "value_date"],
    ["nps", "value_number"],
    ["csat", "value_number"],
    ["ces", "value_number"],
    ["rating", "value_number"],
    ["number", "value_number"],
    ["text", "value_text"],
    ["categorical", "value_text"],
  ] as const)("returns %s → %s", (input, expected) => {
    expect(getValueFieldByType(input)).toBe(expected);
  });
});

describe("toLocalDateTimeInput", () => {
  test("formats valid ISO date", () => {
    const result = toLocalDateTimeInput("2026-03-15T14:30:00.000Z");
    expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/);
  });

  test("returns empty string for invalid date", () => {
    expect(toLocalDateTimeInput("not-a-date")).toBe("");
  });
});

describe("toISOOrUndefined", () => {
  test("returns ISO string for valid input", () => {
    expect(toISOOrUndefined("2026-03-15T14:30")).toMatch(/2026-03-15/);
  });

  test("returns undefined for empty string", () => {
    expect(toISOOrUndefined("")).toBeUndefined();
  });

  test("returns undefined for undefined", () => {
    expect(toISOOrUndefined(undefined)).toBeUndefined();
  });

  test("returns undefined for invalid date", () => {
    expect(toISOOrUndefined("not-a-date")).toBeUndefined();
  });
});

describe("mapRecordToValues", () => {
  test("maps a full record", () => {
    const record = makeRecord({
      value_text: "hello",
      value_number: 42,
      source_id: "s1",
      source_name: "Survey",
      metadata: { tag: "vip", nested: { a: 1 } },
    });
    const result = mapRecordToValues(record);
    expect(result.id).toBe("rec-1");
    expect(result.value_text).toBe("hello");
    expect(result.value_number).toBe("42");
    expect(result.source_id).toBe("s1");
  });

  test("handles nullish optional fields", () => {
    const record = makeRecord({ value_number: undefined, source_id: undefined });
    const result = mapRecordToValues(record);
    expect(result.value_number).toBe("");
    expect(result.source_id).toBe("");
  });
});

describe("getReadOnlyMetadataEntries", () => {
  test("returns every metadata value, strings as-is and the rest as JSON", () => {
    const record = makeRecord({
      metadata: { device: "desktop", count: 5, finished: true, nested: { a: 1 } },
    });
    const result = getReadOnlyMetadataEntries(record);
    expect(result).toEqual([
      { key: "device", value: "desktop" },
      { key: "count", value: "5" },
      { key: "finished", value: "true" },
      { key: "nested", value: '{"a":1}' },
    ]);
  });

  test("returns empty array when no metadata", () => {
    expect(getReadOnlyMetadataEntries(makeRecord())).toEqual([]);
  });

  test("leaves out an embedded_data object, which has its own rows", () => {
    const record = makeRecord({ metadata: { finished: true, embedded_data: { brand: "AEG" } } });
    expect(getReadOnlyMetadataEntries(record)).toEqual([{ key: "finished", value: "true" }]);
  });

  test.each([
    ["an array", ["AEG"], '["AEG"]'],
    ["a string", "AEG", "AEG"],
  ])("keeps an embedded_data value that is %s, so nothing is hidden", (_label, value, shown) => {
    const record = makeRecord({ metadata: { embedded_data: value } });
    expect(getReadOnlyMetadataEntries(record)).toEqual([{ key: "embedded_data", value: shown }]);
  });
});

describe("getEmbeddedDataEntries", () => {
  test("returns one row per field, sorted by name, with scalars as text", () => {
    const record = makeRecord({
      metadata: { finished: true, embedded_data: { plan: "pro", score: 0, brand: "AEG", trial: false } },
    });
    expect(getEmbeddedDataEntries(record)).toEqual([
      { key: "brand", value: "AEG" },
      { key: "plan", value: "pro" },
      { key: "score", value: "0" },
      { key: "trial", value: "false" },
    ]);
  });

  test("returns empty array when the record has no embedded data", () => {
    expect(getEmbeddedDataEntries(makeRecord())).toEqual([]);
    expect(getEmbeddedDataEntries(makeRecord({ metadata: { finished: true } }))).toEqual([]);
  });

  test.each([
    ["a string", "AEG"],
    ["an array", ["AEG"]],
    ["null", null],
  ])("ignores embedded_data that is %s rather than an object", (_label, value) => {
    expect(getEmbeddedDataEntries(makeRecord({ metadata: { embedded_data: value } }))).toEqual([]);
  });
});

describe("parseNumberValue", () => {
  test.each([
    ["42", 42],
    ["3.14", 3.14],
    ["-1", -1],
    ["", null],
    ["  ", null],
    ["abc", null],
    ["Infinity", null],
  ])("parseNumberValue(%s) → %s", (input, expected) => {
    expect(parseNumberValue(input)).toBe(expected);
  });
});

describe("isPresetSourceType", () => {
  test("returns true for preset values", () => {
    expect(isPresetSourceType("survey")).toBe(true);
    expect(isPresetSourceType("nps_campaign")).toBe(true);
  });

  test("returns false for custom values", () => {
    expect(isPresetSourceType("custom_type")).toBe(false);
    expect(isPresetSourceType("")).toBe(false);
  });
});

describe("formatSourceType", () => {
  test("maps known source types", () => {
    expect(formatSourceType("formbricks", t)).toBe("workspace.unify.formbricks_surveys");
    expect(formatSourceType("formbricks_survey", t)).toBe("workspace.unify.formbricks_surveys");
    expect(formatSourceType("csv", t)).toBe("workspace.unify.csv_import");
  });

  test("returns raw value for unknown types", () => {
    expect(formatSourceType("custom", t)).toBe("custom");
  });
});

describe("formatFieldType", () => {
  test("capitalizes non-acronym types", () => {
    expect(formatFieldType("text")).toBe("Text");
    expect(formatFieldType("categorical")).toBe("Categorical");
    expect(formatFieldType("number")).toBe("Number");
    expect(formatFieldType("date")).toBe("Date");
  });

  test("upper-cases acronym types", () => {
    expect(formatFieldType("nps")).toBe("NPS");
    expect(formatFieldType("csat")).toBe("CSAT");
    expect(formatFieldType("ces")).toBe("CES");
  });

  test("returns empty string unchanged", () => {
    expect(formatFieldType("")).toBe("");
  });
});

describe("formatFieldTypeLabel", () => {
  test("maps every icon-mapped field type to a translation key", () => {
    // The keys of FIELD_TYPE_ICON_MAP are the types the pick-list can render an icon for, and the
    // icon's aria-label is their only textual form — so each one must resolve to a key, not to the
    // re-cased raw value.
    for (const fieldType of Object.keys(FIELD_TYPE_ICON_MAP)) {
      expect(formatFieldTypeLabel(fieldType, t)).toBe(`workspace.unify.field_type_label_${fieldType}`);
    }
  });

  test("falls back to the re-cased raw value for an unmapped type", () => {
    expect(formatFieldTypeLabel("ranking", t)).toBe("Ranking");
    expect(formatFieldTypeLabel("", t)).toBe("");
  });
});

describe("resolveFeedbackDisplayText", () => {
  test("prefers the translation when present and different from the original", () => {
    const result = resolveFeedbackDisplayText(
      makeRecord({
        value_text: "Großartig",
        value_text_translated: "Great",
        translation_lang_key: "en",
      })
    );
    expect(result).toEqual({
      text: "Great",
      original: "Großartig",
      isTranslated: true,
      langKey: "en",
    });
  });

  test("falls back to the original when no translation exists", () => {
    const result = resolveFeedbackDisplayText(makeRecord({ value_text: "Hello" }));
    expect(result).toEqual({
      text: "Hello",
      original: "Hello",
      isTranslated: false,
      langKey: null,
    });
  });

  test.each([["   "], [""]])(
    "ignores empty/whitespace-only translations (%j) and shows the original",
    (translated) => {
      const result = resolveFeedbackDisplayText(
        makeRecord({ value_text: "Original", value_text_translated: translated, translation_lang_key: "en" })
      );
      expect(result.text).toBe("Original");
      expect(result.isTranslated).toBe(false);
      expect(result.langKey).toBeNull();
    }
  );

  test("does not flag a translation identical to the original", () => {
    const result = resolveFeedbackDisplayText(
      makeRecord({ value_text: "Same", value_text_translated: "Same", translation_lang_key: "en" })
    );
    expect(result.text).toBe("Same");
    expect(result.isTranslated).toBe(false);
    expect(result.langKey).toBeNull();
  });

  test("drops the language key when there is no usable translation", () => {
    const result = resolveFeedbackDisplayText(
      makeRecord({ value_text: "Hello", translation_lang_key: "en" })
    );
    expect(result.isTranslated).toBe(false);
    expect(result.langKey).toBeNull();
  });

  test("returns null text when the record carries no text value at all", () => {
    const result = resolveFeedbackDisplayText(makeRecord({ value_text: undefined }));
    expect(result.text).toBeNull();
    expect(result.original).toBeNull();
    expect(result.isTranslated).toBe(false);
  });

  test("preserves an empty-string original (does not collapse to null)", () => {
    const result = resolveFeedbackDisplayText(makeRecord({ value_text: "" }));
    expect(result.text).toBe("");
    expect(result.original).toBe("");
  });
});
