import { createDbService } from '@/server/services/db.js';
/**
 * SSR prefetch for the MyPurchases island.
 *
 * Seeds qk.purchases() with the user's full purchase list from the DB.
 * staleTime on useMyPurchases = 60s — seeded data is complete; client will
 * refetch after 1 minute as normal. No regression risk.
 *
 * Requires auth: purchases page already redirects to /login if no session,
 * so userId is always present when this runs.
 */

import type { PrefetchFn } from '@/lib/query/ssr';
import { qk } from '@/lib/query/keys';
import { listByUser } from '@/server/db/queries/purchases';
import { env } from '@/server/env';

export function prefetchPurchases(locals: App.Locals): PrefetchFn {
  return async (qc) => {
    const userId = locals.session?.userId;
    if (!userId || !env.DATABASE_URL) return;

    const db = createDbService(env);
    const { active, history, stats } = await listByUser(db, userId);
    const data = {
      active,
      history,
      totalSavings: Number(stats.totalSavings),
      businessCount: stats.businessCount,
    };

    await qc.prefetchQuery({
      queryKey: qk.purchases(),
      queryFn: () => Promise.resolve(data),
    });
  };
}
