import { describe, it, expect } from "vitest";
import { getWeekDateRange } from "./weekDateRange.js";

describe("getWeekDateRange", () => {
  it("returns Monday/Sunday for a mid-week date", () => {
    // 2026-04-15 is a Wednesday
    const result = getWeekDateRange("2026-04-15T10:00:00");
    expect(result.start).toBe("13.04.2026");
    expect(result.end).toBe("19.04.2026");
  });

  it("returns Monday/Sunday for a Sunday input", () => {
    const result = getWeekDateRange("2026-04-19T10:00:00");
    expect(result.start).toBe("13.04.2026");
    expect(result.end).toBe("19.04.2026");
  });

  it("returns Monday/Sunday for a Monday input", () => {
    const result = getWeekDateRange("2026-04-13T10:00:00");
    expect(result.start).toBe("13.04.2026");
    expect(result.end).toBe("19.04.2026");
  });

  it("returns empty strings for invalid input", () => {
    expect(getWeekDateRange("not-a-date")).toEqual({ start: "", end: "" });
  });

  it("returns empty strings for undefined input", () => {
    expect(getWeekDateRange(undefined)).toEqual({ start: "", end: "" });
  });

  // TZ §4.1.16.8: week range must be calendar week Mon–Sun (ISO week)
  // Verify that the range spans exactly 6 days (Sun - Mon = 6 day delta)
  it("end date is always exactly 6 days after start date", () => {
    const cases = [
      "2026-04-15T10:00:00",  // Wednesday
      "2026-04-13T00:00:00",  // Monday
      "2026-04-19T23:59:59",  // Sunday
      "2026-01-01T12:00:00",  // New Year's Day
    ];
    for (const iso of cases) {
      const { start, end } = getWeekDateRange(iso);
      const [sd, sm, sy] = start.split(".").map(Number);
      const [ed, em, ey] = end.split(".").map(Number);
      const startMs = new Date(sy!, sm! - 1, sd!).getTime();
      const endMs = new Date(ey!, em! - 1, ed!).getTime();
      const daysDiff = Math.round((endMs - startMs) / 86400000);
      expect(daysDiff).toBe(6);
    }
  });

  // TZ §4.1.16.8: "dd.MM.yyyy" format (leading zeros required)
  it("formats dates with leading zeros", () => {
    // 2026-01-05 is a Monday
    const { start, end } = getWeekDateRange("2026-01-05T10:00:00");
    expect(start).toBe("05.01.2026");
    expect(end).toBe("11.01.2026");
  });

  // TZ §4.1.16.8: week starts on Monday (ISO standard)
  it("Saturday input yields same Mon–Sun week as adjacent Monday", () => {
    const sat = getWeekDateRange("2026-04-18T10:00:00");  // Saturday
    const mon = getWeekDateRange("2026-04-13T10:00:00");  // Monday of same week
    expect(sat.start).toBe(mon.start);
    expect(sat.end).toBe(mon.end);
  });
});
