import { apiGet } from "./client";
import { TENANT_DOMAIN } from "./config";
import type { ApiProduct, ProductsResponse } from "./types";

const PAGE_SIZE = 100;

export async function getPublishedProducts(): Promise<ApiProduct[]> {
  const first = await apiGet<ProductsResponse>(
    `/tenants/${TENANT_DOMAIN}/products?page=1&pageSize=${PAGE_SIZE}`,
  );

  const items = [...first.items];
  const totalPages = Math.max(1, Math.ceil(first.total / PAGE_SIZE));

  for (let page = 2; page <= totalPages; page += 1) {
    const next = await apiGet<ProductsResponse>(
      `/tenants/${TENANT_DOMAIN}/products?page=${page}&pageSize=${PAGE_SIZE}`,
    );
    items.push(...next.items);
  }

  return items;
}
