import { describe, it, expect } from "vitest";
import { formatYyyymmdd, parseYyyymmdd, generateDateRange, findPageIndex } from "./dateRange.js";

describe("formatYyyymmdd", () => {
  it("formats a Date to yyyymmdd", () => {
    expect(formatYyyymmdd(new Date(2026, 3, 16))).toBe("20260416");
  });

  it("pads single-digit month and day", () => {
    expect(formatYyyymmdd(new Date(2026, 0, 5))).toBe("20260105");
  });
});

describe("parseYyyymmdd", () => {
  it("parses yyyymmdd into Date", () => {
    const d = parseYyyymmdd("20260416");
    expect(d.getFullYear()).toBe(2026);
    expect(d.getMonth()).toBe(3);
    expect(d.getDate()).toBe(16);
  });
});

describe("generateDateRange", () => {
  it("generates dates from today-daysBefore to today+daysAfter inclusive", () => {
    const today = new Date(2026, 3, 16);
    const range = generateDateRange(today, 2, 3);
    expect(range).toHaveLength(6);
    expect(range[0]).toBe("20260414");
    expect(range[2]).toBe("20260416");
    expect(range[5]).toBe("20260419");
  });

  it("handles zero-range", () => {
    const today = new Date(2026, 3, 16);
    expect(generateDateRange(today, 0, 0)).toEqual(["20260416"]);
  });

  it("handles month boundaries", () => {
    const today = new Date(2026, 3, 1);
    const range = generateDateRange(today, 2, 0);
    expect(range).toEqual(["20260330", "20260331", "20260401"]);
  });
});

describe("findPageIndex", () => {
  it("finds page index for the given date at pageSize=7", () => {
    const dates = ["20260414", "20260415", "20260416", "20260417", "20260418", "20260419", "20260420", "20260421", "20260422"];
    expect(findPageIndex(dates, "20260414", 7)).toBe(0);
    expect(findPageIndex(dates, "20260420", 7)).toBe(0);
    expect(findPageIndex(dates, "20260421", 7)).toBe(1);
    expect(findPageIndex(dates, "20260422", 7)).toBe(1);
  });

  it("returns 0 when date not found", () => {
    const dates = ["20260414", "20260415"];
    expect(findPageIndex(dates, "20260999", 7)).toBe(0);
  });
});
