import type { DrizzleClient } from '@/server/db/client';
import type { LoadCtx } from '@/server/page-layout/types';
import type { Config } from './config';
import type { HotDealWindow } from '@/server/catalog/public/hot';
import type { DealCardDeal } from '@/components/ui/domain/DealCard';
import { queryHotDealsByWindowCards } from '@/features/feed/FeedDataLoader';
import { captureCaught } from '@/server/observability/capture.server';

export interface HotDealsModuleData {
  deals: DealCardDeal[];
  activeWindow: HotDealWindow;
}

export async function loadData(
  db: DrizzleClient,
  config: Config,
  ctx: LoadCtx,
): Promise<HotDealsModuleData | null> {
  try {
    const deals24h = await queryHotDealsByWindowCards(
      db,
      '24h',
      config.limit,
      ctx.hotDealThreshold,
    );
    if (deals24h.length > 0) {
      return { deals: deals24h, activeWindow: '24h' };
    }
    // No 24h data — fall back to 7d window
    const deals7d = await queryHotDealsByWindowCards(db, '7d', config.limit, ctx.hotDealThreshold);
    return { deals: deals7d, activeWindow: '7d' };
  } catch (err) {
    captureCaught(err, {
      scope: 'server.page-layout.modules.deal-row-hot-deals.loadData',
      severity: 'warning',
    });
    return null;
  }
}
