import { describe, expect, it } from "vitest";
import {
  INITIAL_PAGER_STATE,
  advancePager,
  pageNumber,
  retreatPager,
  type PagerState,
} from "./cursor";

describe("cursor pager state machine", () => {
  it("starts on page 1 with a null cursor", () => {
    expect(INITIAL_PAGER_STATE.cursor).toBeNull();
    expect(pageNumber(INITIAL_PAGER_STATE)).toBe(1);
  });

  it("advances and keeps a cursor stack for going back", () => {
    let state: PagerState = INITIAL_PAGER_STATE;
    state = advancePager(state, "c2");
    expect(state.cursor).toBe("c2");
    expect(pageNumber(state)).toBe(2);
    state = advancePager(state, "c3");
    expect(state.cursor).toBe("c3");
    expect(pageNumber(state)).toBe(3);

    state = retreatPager(state);
    expect(state.cursor).toBe("c2");
    expect(pageNumber(state)).toBe(2);
    state = retreatPager(state);
    expect(state.cursor).toBeNull();
    expect(pageNumber(state)).toBe(1);
  });

  it("ignores advance with a null cursor (no next page)", () => {
    const state = advancePager(INITIAL_PAGER_STATE, null);
    expect(state).toEqual(INITIAL_PAGER_STATE);
  });

  it("ignores retreat on the first page", () => {
    const state = retreatPager(INITIAL_PAGER_STATE);
    expect(state).toEqual(INITIAL_PAGER_STATE);
  });
});
