import { eq } from 'drizzle-orm';
import type { DrizzleClient } from '@/server/db/client';
import type { LoadCtx } from '@/server/page-layout/types';
import { configSchema, type Config } from './config';
import {
  queryActiveDeals,
  toDealCardDeal,
  loadTrendingDeals,
} from '@/features/feed/FeedDataLoader';
import { dealCategories } from '@/server/db/schema';
import { captureCaught } from '@/server/observability/capture.server';

/**
 * Resolve a category enum slug (e.g. 'MEAL') to a dealCategories UUID by
 * matching the `dealType` text field (stored uppercase). Returns undefined
 * if no matching category row exists.
 */
async function resolveSlugToCategoryId(
  db: DrizzleClient,
  slug: string,
): Promise<string | undefined> {
  const rows = await db
    .select({ id: dealCategories.id })
    .from(dealCategories)
    .where(eq(dealCategories.dealType, slug.toUpperCase()))
    .limit(1);
  return rows[0]?.id;
}

export async function loadData(db: DrizzleClient, config: Config, _ctx: LoadCtx) {
  try {
    // Defense-in-depth: re-validate config at the server boundary
    configSchema.parse(config);

    if (config.sort === 'trending') {
      return await loadTrendingDeals(db, config.limit);
    }

    // Resolve category slug → UUID. If filter absent, do not constrain by category.
    // If a slug is provided but resolves to no row, return empty (explicit filter,
    // no matches) — mirrors deal-row-category behavior.
    let categoryId: string | undefined;
    if (config.filters.category) {
      categoryId = await resolveSlugToCategoryId(db, config.filters.category);
      if (!categoryId) return [];
    }

    const rows = await queryActiveDeals(db, {
      limit: config.limit,
      lowStock: config.filters.lowStock,
      nearExpiry: config.filters.nearExpiry,
      categoryId,
      dealType:
        config.filters.dealType === 'GROUP'
          ? 'GROUP'
          : config.filters.dealType
            ? 'COUPON'
            : undefined,
    });
    return rows.map(toDealCardDeal);
  } catch (err) {
    captureCaught(err, {
      scope: 'server.page-layout.modules.deal-row-custom-query.loadData',
      severity: 'warning',
    });
    return null;
  }
}
