import 'server-only'

/**
 * Run an `.in(column, ids)` query in chunks.
 *
 * PostgREST filters travel in the URL, so a long id list overflows the
 * request (an admin sees every trip on the platform — requirement,
 * 2026-09-11 — and a list of thousands of UUIDs is hundreds of KB).
 * Supabase also caps a single response at 1000 rows by default. Chunking keeps
 * every request small and every response under the cap.
 */
export const IN_CHUNK_SIZE = 150

export async function inChunks<T>(
  ids: readonly string[],
  run: (chunk: string[]) => PromiseLike<{ data: T[] | null; error: unknown }>,
): Promise<{ data: T[]; error: unknown }> {
  const unique = [...new Set(ids)]
  const out: T[] = []
  for (let i = 0; i < unique.length; i += IN_CHUNK_SIZE) {
    const { data, error } = await run(unique.slice(i, i + IN_CHUNK_SIZE))
    if (error) return { data: out, error }
    out.push(...(data ?? []))
  }
  return { data: out, error: null }
}

/** Every row of a query, paging past the 1000-row response cap. */
export async function allPages<T>(
  page: (from: number, to: number) => PromiseLike<{ data: T[] | null; error: unknown }>,
  pageSize = 1000,
): Promise<T[]> {
  const out: T[] = []
  for (let from = 0; ; from += pageSize) {
    const { data, error } = await page(from, from + pageSize - 1)
    if (error || !data) break
    out.push(...data)
    if (data.length < pageSize) break
  }
  return out
}
