import { createClient } from '@/lib/supabase/server'; import { serviceHeaders, supabaseUrl } from '@/lib/agency'; import type { AdDailyRow } from '@/lib/metrics'; const PAGE = 1000; const MAX_ROWS = 200000; export async function fetchAdDailyPaged(opts: { tenantId: string | null; useServiceRole: boolean; since: string; until?: string; }): Promise { const { tenantId, useServiceRole, since, until } = opts; const out: AdDailyRow[] = []; if (useServiceRole) { const headers = serviceHeaders(); const base = supabaseUrl(); if (!headers || !base) return []; const tid = tenantId ? `&tenant_id=eq.${encodeURIComponent(tenantId)}` : ''; const untilF = until ? `&date=lte.${until}` : ''; for (let offset = 0; offset < MAX_ROWS; offset += PAGE) { const r = await fetch( `${base}/rest/v1/ad_daily?select=*&date=gte.${since}${untilF}${tid}&order=date.desc&limit=${PAGE}&offset=${offset}`, { headers, cache: 'no-store' } ); if (!r.ok) break; const chunk = (await r.json()) as AdDailyRow[]; out.push(...chunk); if (chunk.length < PAGE) break; } return out; } const supabase = await createClient(); for (let offset = 0; offset < MAX_ROWS; offset += PAGE) { let q = supabase .from('ad_daily') .select('*') .gte('date', since) .order('date', { ascending: false }) .range(offset, offset + PAGE - 1); if (until) q = q.lte('date', until); const { data, error } = await q; if (error) break; const chunk = (data as AdDailyRow[]) || []; out.push(...chunk); if (chunk.length < PAGE) break; } return out; } export function adDailyLookbackSince(): string { const since = new Date(); since.setUTCDate( since.getUTCDate() - (Math.ceil((Date.now() - Date.UTC(2025, 0, 1)) / 86400000) + 14) ); return since.toISOString().slice(0, 10); }