// TODO: types (don't even sweat validation)
// TODO: do sweat error handling
type Cursor = { refSnowflake: string; offset: number; sortOrder: string };

export const get = (
  cursor?: Cursor,
): Promise<{ listings: any[]; nextCursor: Cursor | undefined }> =>
  fetch(
    `https://cohost.org/api/v1/trpc/artistAlley.getListingsForDisplay?batch=1&input=${
      encodeURI(
        JSON.stringify({
          "0": {
            adultDisplayMode: "include",
            categories: [],
            categoryMatch: "all",
            sortOrder: "newest",
            cursor,
          },
        }),
      )
    }`,
  ).then(async (r) => {
    const json = (await r.json())[0];
    if (json.error) throw json.error;

    const j = json.result.data;
    return {
      listings: j.listings.map((l: any) => ({
        ...l,
        author: j.relevantProjects[l.projectId],
      })),
      nextCursor: j.nextCursor,
    };
  });

export const get_all = async (cursor?: Cursor): Promise<any[]> => {
  const { listings, nextCursor } = await get(cursor);
  return nextCursor ? [...listings, ...(await get_all(nextCursor))] : listings;
};

if (import.meta.main) {
    const got = await get_all();
    console.log(got);
    console.log(got.length);
};
