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

async function resolveSlug(
  db: DrizzleClient,
  config: Config,
  ctx: LoadCtx,
): Promise<string | null> {
  if (config.categorySlug) return config.categorySlug;
  if (!config.categoryId) return null;
  ctx.resolvedCategorySlugs ??= new Map<string, string>();
  const cached = ctx.resolvedCategorySlugs.get(config.categoryId);
  if (cached !== undefined) return cached;
  const result = (await db.execute(
    sql`SELECT slug FROM deal_categories WHERE id = ${config.categoryId} LIMIT 1`,
  )) as { rows: Array<{ slug: string }> };
  const slug = (result.rows[0] as { slug: string } | undefined)?.slug ?? null;
  if (slug) ctx.resolvedCategorySlugs.set(config.categoryId, slug);
  return slug;
}

export async function loadData(db: DrizzleClient, config: Config, ctx: LoadCtx) {
  try {
    if (!config.categoryId) return { deals: [], categorySlug: null };
    const [categorySlug, hotThreshold] = await Promise.all([
      resolveSlug(db, config, ctx),
      ctx.hotDealThreshold !== undefined ? ctx.hotDealThreshold : getHotDealThreshold(db),
    ]);
    // Fast path: filter by category from pre-fetched pool (guest pages).
    if (ctx.prefetchedDeals) {
      const rows = filterPrefetchedPool(ctx.prefetchedDeals, {
        limit: config.limit,
        categoryId: config.categoryId,
      });
      return { deals: rows.map((r) => toDealCardDeal(r, hotThreshold)), categorySlug };
    }
    const rows = await queryActiveDeals(db, { limit: config.limit, categoryId: config.categoryId });
    return { deals: rows.map((r: DealRow) => toDealCardDeal(r, hotThreshold)), categorySlug };
  } catch (err) {
    captureCaught(err, {
      scope: 'server.page-layout.modules.deal-row-category.loadData',
      severity: 'warning',
    });
    return null;
  }
}
