import type { DrizzleClient } from '@/server/db/client';
import type { LoadCtx } from '@/server/page-layout/types';
import type { Config } from './config';
import {
  queryForYouCards,
  filterPrefetchedPool,
  toDealCardDeal,
} from '@/features/feed/FeedDataLoader';
import { captureCaught } from '@/server/observability/capture.server';

export async function loadData(db: DrizzleClient, config: Config, ctx: LoadCtx) {
  try {
    // Fast path: use pre-fetched deal pool (guest pages — one shared round-trip).
    if (ctx.prefetchedDeals) {
      const rows = filterPrefetchedPool(ctx.prefetchedDeals, { limit: config.limit });
      return rows.map((r) => toDealCardDeal(r, ctx.hotDealThreshold));
    }
    return await queryForYouCards(db, config.limit, ctx.hotDealThreshold);
  } catch (err) {
    captureCaught(err, {
      scope: 'server.page-layout.modules.deal-row-auto-scroll.loadData',
      severity: 'warning',
    });
    return null;
  }
}
