import { describe, expect, test } from "vitest";
import {
  DATE_DISPLAY_OPTIONS,
  diffInDays,
  formatDateForDisplay,
  formatDateTimeForDisplay,
  formatDateWithOrdinal,
  formatLocalDay,
  formatStoredDateValue,
  getDateFnsLocale,
  getFormattedDateTimeString,
  isValidDateString,
  parseLocalDay,
  parseStoredDay,
} from "./datetime";

describe("datetime utils", () => {
  test("diffInDays calculates the difference in days between two dates", () => {
    const date1 = new Date("2025-05-01");
    const date2 = new Date("2025-05-06");
    expect(diffInDays(date1, date2)).toBe(5);
  });

  test("formatDateWithOrdinal formats a date using the provided locale", () => {
    // Create a date that's fixed to May 6, 2025 at noon UTC
    // Using noon ensures the date won't change in most timezones
    const date = new Date(Date.UTC(2025, 4, 6, 12, 0, 0));

    expect(formatDateWithOrdinal(date)).toBe(
      new Intl.DateTimeFormat("en-US", {
        weekday: "long",
        year: "numeric",
        month: "long",
        day: "numeric",
      }).format(date)
    );
  });

  test("formatDateForDisplay uses the provided locale", () => {
    const date = new Date(Date.UTC(2025, 4, 6, 12, 0, 0));

    expect(formatDateForDisplay(date, "de-DE")).toBe(
      new Intl.DateTimeFormat("de-DE", {
        year: "numeric",
        month: "short",
        day: "numeric",
      }).format(date)
    );
  });

  test("formatDateTimeForDisplay uses the provided locale", () => {
    const date = new Date(Date.UTC(2025, 4, 6, 12, 30, 0));

    expect(formatDateTimeForDisplay(date, "fr-FR")).toBe(
      new Intl.DateTimeFormat("fr-FR", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "numeric",
        minute: "2-digit",
      }).format(date)
    );
  });

  test("isValidDateString validates correct date strings", () => {
    expect(isValidDateString("2025-05-06")).toBeTruthy();
    expect(isValidDateString("06-05-2025")).toBeTruthy();
    expect(isValidDateString("2025/05/06")).toBeFalsy();
    expect(isValidDateString("invalid-date")).toBeFalsy();
  });

  test("getFormattedDateTimeString formats in UTC by default and tags the zone", () => {
    const date = new Date("2025-05-06T14:30:00.000Z");
    expect(getFormattedDateTimeString(date)).toBe("2025-05-06 14:30:00 UTC");
  });

  test("getFormattedDateTimeString formats in the given IANA time zone with a zone marker", () => {
    const date = new Date("2026-01-01T20:00:00.000Z");
    // Asia/Manila is UTC+8, so the formatted date crosses midnight
    expect(getFormattedDateTimeString(date, "Asia/Manila")).toBe("2026-01-02 04:00:00 GMT+8");
  });

  test("getFormattedDateTimeString supports half-hour offset time zones", () => {
    const date = new Date("2026-01-01T20:00:00.000Z");
    // Asia/Kolkata is UTC+5:30. The zone marker resolves to either the CLDR abbreviation
    // ("IST") or the numeric offset ("GMT+5:30") depending on the runtime's ICU data, so
    // assert the offset math and accept either marker form.
    expect(getFormattedDateTimeString(date, "Asia/Kolkata")).toMatch(/^2026-01-02 01:30:00 (IST|GMT\+5:30)$/);
  });

  test("getFormattedDateTimeString formats in UTC when the time zone is explicitly UTC", () => {
    const date = new Date("2026-01-01T20:00:00.000Z");
    expect(getFormattedDateTimeString(date, "UTC")).toBe("2026-01-01 20:00:00 UTC");
  });

  test("getFormattedDateTimeString degrades to UTC when the time zone is invalid", () => {
    const date = new Date("2026-01-01T20:00:00.000Z");
    // An unknown IANA zone makes Intl.DateTimeFormat throw; the export must not fail.
    expect(getFormattedDateTimeString(date, "Not/AZone")).toBe("2026-01-01 20:00:00 UTC");
  });
});

describe("formatLocalDay / parseLocalDay", () => {
  test("serialises the local calendar day, zero-padded", () => {
    // Late in the day on purpose: a UTC-based serialiser would roll this to the 6th east of UTC.
    expect(formatLocalDay(new Date(2026, 7, 5, 23, 30))).toBe("2026-08-05");
    expect(formatLocalDay(new Date(2026, 0, 1, 0, 0))).toBe("2026-01-01");
    expect(formatLocalDay(new Date(2026, 11, 31, 12, 0))).toBe("2026-12-31");
  });

  test("round-trips through parseLocalDay to local midnight", () => {
    const parsed = parseLocalDay("2026-08-05");

    expect([parsed.getFullYear(), parsed.getMonth(), parsed.getDate()]).toEqual([2026, 7, 5]);
    expect([parsed.getHours(), parsed.getMinutes()]).toEqual([0, 0]);
    expect(formatLocalDay(parsed)).toBe("2026-08-05");
  });

  test.each(["2026-01-01", "2026-03-08", "2026-08-05", "2026-11-01", "2026-12-31"])(
    "is its own inverse for %s",
    (day) => {
      expect(formatLocalDay(parseLocalDay(day))).toBe(day);
    }
  );
});

describe("parseStoredDay", () => {
  test("reads the calendar day out of a stored ISO timestamp without shifting it", () => {
    // Segment and contact-attribute values are stored at midnight UTC. Parsing the whole string as an
    // instant would land on the 4th for viewers west of UTC; the day named in the string must win.
    const parsed = parseStoredDay("2026-08-05T00:00:00.000Z");

    expect(parsed && formatLocalDay(parsed)).toBe("2026-08-05");
    expect(parsed && [parsed.getHours(), parsed.getMinutes()]).toEqual([0, 0]);
  });

  test("parses a bare yyyy-MM-dd day, as validation rules store it", () => {
    const parsed = parseStoredDay("2026-01-31");

    expect(parsed && [parsed.getFullYear(), parsed.getMonth(), parsed.getDate()]).toEqual([2026, 0, 31]);
  });

  test.each(["2026-08-05T25:99:99Z", "2026-08-05Tnot-a-time", "2026-08-05T"])(
    "keeps the day when only the time part is malformed: %s",
    (value) => {
      // Deliberate: the day is what the picker shows, and the `<input type="date">` this replaced
      // split on "T" the same way. Blanking a readable day over a broken suffix would lose data.
      const parsed = parseStoredDay(value);

      expect(parsed && formatLocalDay(parsed)).toBe("2026-08-05");
    }
  );

  test("returns null when there is no stored value", () => {
    expect(parseStoredDay("")).toBeNull();
    expect(parseStoredDay(null)).toBeNull();
    expect(parseStoredDay(undefined)).toBeNull();
  });

  test.each([
    ["not-a-date", "unparseable text"],
    ["2026-13-45", "an out-of-range day that Date would roll over to 2027-02-14"],
    ["05/08/2026", "a non-ISO order"],
    ["2026-9-7", 'an unpadded day, which an <input type="date"> also rejected'],
  ])("returns null for %s (%s)", (value) => {
    expect(parseStoredDay(value)).toBeNull();
  });
});

describe("getDateFnsLocale", () => {
  // The calendar reads month, weekday and first-day-of-week off the returned locale, so the assertions
  // are on the resolved locale's `code` rather than on object identity.
  test.each([
    ["de-DE", "de"],
    ["es-ES", "es"],
    ["fr-FR", "fr"],
    ["hu-HU", "hu"],
    ["ja-JP", "ja"],
    ["nl-NL", "nl"],
    ["ro-RO", "ro"],
    ["ru-RU", "ru"],
    ["sv-SE", "sv"],
    ["tr-TR", "tr"],
    ["en-US", "en-US"],
  ])("maps the app locale %s to date-fns %s", (appLocale, expected) => {
    expect(getDateFnsLocale(appLocale).code).toBe(expected);
  });

  test.each([
    ["pt-BR", "pt-BR"],
    ["pt-PT", "pt"],
    ["pt", "pt-BR"],
  ])("keeps Portuguese variants apart: %s", (appLocale, expected) => {
    // pt-BR and pt-PT are different locales, so neither may be reached by cutting the tag to "pt".
    expect(getDateFnsLocale(appLocale).code).toBe(expected);
  });

  test.each([
    ["zh-Hans-CN", "zh-CN"],
    ["zh-cn", "zh-CN"],
    ["zh-Hant-TW", "zh-TW"],
    ["zh-tw", "zh-TW"],
    ["zh-hk", "zh-TW"],
    ["zh", "zh-CN"],
  ])("resolves Chinese script tags: %s", (appLocale, expected) => {
    expect(getDateFnsLocale(appLocale).code).toBe(expected);
  });

  test("is case-insensitive about the tag", () => {
    expect(getDateFnsLocale("DE-de").code).toBe("de");
    expect(getDateFnsLocale("PT-br").code).toBe("pt-BR");
  });

  test("falls back to en-US for an unset, empty or unknown locale", () => {
    // A survey language that never became an app locale must not throw.
    expect(getDateFnsLocale().code).toBe("en-US");
    expect(getDateFnsLocale("").code).toBe("en-US");
    expect(getDateFnsLocale("xx-YY").code).toBe("en-US");
    expect(getDateFnsLocale("uz").code).toBe("en-US");
  });

  test("accepts a bare language tag without a region", () => {
    expect(getDateFnsLocale("de").code).toBe("de");
    expect(getDateFnsLocale("ja").code).toBe("ja");
  });
});

describe("formatStoredDateValue: a stored date in the app's date format (P65)", () => {
  test("a calendar date reads as that day only, whatever the viewer's time zone", () => {
    expect(formatStoredDateValue("2026-11-04", "en-US", "Pacific/Honolulu")).toBe("Nov 4, 2026");
    expect(formatStoredDateValue("2026-11-04", "en-GB", "Asia/Tokyo")).toBe("4 Nov 2026");
  });

  test("a timestamp reads as the same day format plus the time, in the viewer's time zone", () => {
    expect(formatStoredDateValue("2026-11-04T10:12:30.000Z", "en-GB", "UTC")).toBe("4 Nov 2026, 10:12");
    expect(formatStoredDateValue("2026-11-04T10:12:30.000Z", "en-US", "UTC")).toMatch(
      /^Nov 4, 2026, 10:12\sAM$/
    );
    // 23:30 UTC is already the next morning in Tokyo.
    expect(formatStoredDateValue("2026-11-04T23:30:00Z", "en-GB", "Asia/Tokyo")).toBe("5 Nov 2026, 8:30");
  });

  test("a timestamp at exactly UTC midnight is a day written as a timestamp: that day only, as the picker reads it", () => {
    // An SDK's `new Date("2026-08-05")` arrives as 2026-08-05T00:00:00.000Z; in New York it would be
    // the evening of the 4th as an instant.
    expect(formatStoredDateValue("2026-08-05T00:00:00.000Z", "en-US", "America/New_York")).toBe(
      "Aug 5, 2026"
    );
    expect(formatStoredDateValue("2026-08-05T00:00:00Z", "en-US", "America/New_York")).toBe("Aug 5, 2026");
    // A second past midnight is a time again.
    expect(formatStoredDateValue("2026-08-05T00:00:01.000Z", "en-US", "America/New_York")).toMatch(
      /^Aug 4, 2026, 8:00\sPM$/
    );
  });

  test("the day format is the date picker's, so the two read alike", () => {
    expect(formatStoredDateValue("2026-11-04", "en-US")).toBe(
      formatDateForDisplay(new Date(Date.UTC(2026, 10, 4)), "en-US", {
        ...DATE_DISPLAY_OPTIONS,
        timeZone: "UTC",
      })
    );
  });

  test.each(["", "gold", "2026-13-45", "04/11/2026", "2026-11-04Tnoon", "1730700000000"])(
    "returns null for %j, which is not a stored date",
    (value) => {
      expect(formatStoredDateValue(value, "en-US")).toBeNull();
    }
  );
});
