import { describe, expect, it } from "vitest";
import { createCursorPager, discoveredPageCount, pageCount } from "./pagination.svelte";

describe("profile pagination counts", () => {
	it("uses the known total for profile lists", () => {
		expect(pageCount(4, 30)).toBe(1);
		expect(pageCount(30, 30)).toBe(1);
		expect(pageCount(31, 30)).toBe(2);
	});

	it("only discovers an extra page when totals are unavailable", () => {
		expect(discoveredPageCount(1, false)).toBe(1);
		expect(discoveredPageCount(1, true)).toBe(2);
		expect(discoveredPageCount(2, true)).toBe(3);
	});

	it("keeps pager lifecycle in one state", async () => {
		let release!: (page: { items: string[] }) => void;
		const pager = createCursorPager(
			{ items: ["first"], cursor: "next" },
			() => new Promise<{ items: string[] }>((resolve) => (release = resolve))
		);

		const loading = pager.select(2);
		expect(pager.state).toEqual({ kind: "loading", page: 1 });
		release({ items: ["second"] });
		await loading;
		expect(pager.state).toEqual({ kind: "at-page", page: 2 });

		const failing = createCursorPager({ items: ["first"], cursor: "next" }, async () => {
			throw new Error("nope");
		});
		await failing.select(2);
		expect(failing.state).toEqual({ kind: "failed", page: 1 });
	});
});
