import { accounting } from "@/lib/accountingClient";

// PostgREST caps each response at 1000 rows, so companies with more journal
// entries than that (e.g. Buildium-imported books) were silently truncated —
// and a query error (statement timeout) used to be swallowed into an empty
// list. Page through all entries on a stable key and throw on error so
// react-query surfaces failures instead of rendering an empty ledger.
const PAGE = 1000;

export async function fetchAllJournalEntries(
  cid: string,
  select: string,
  opts: { ascending?: boolean } = {},
): Promise<any[]> {
  const ascending = opts.ascending ?? false;
  const out: any[] = [];
  for (let offset = 0; ; offset += PAGE) {
    const { data, error } = await accounting
      .from("journal_entries")
      .select(select)
      .eq("company_id", cid)
      .order("date", { ascending })
      .order("created_at", { ascending })
      .order("id", { ascending: true })
      .range(offset, offset + PAGE - 1);
    if (error) throw error;
    const rows = (data ?? []) as any[];
    out.push(...rows);
    if (rows.length < PAGE) break;
  }
  return out;
}
