import { and, asc, eq, gt, isNotNull, lt } from 'drizzle-orm';
import type { DrizzleClient } from '@/server/db/client';
import { dealTranslations, deals } from '@/server/db/schema';
import type { LoadCtx } from '@/server/page-layout/types';
import type { Config } from './config';
import { captureCaught } from '@/server/observability/capture.server';

export interface TickerDeal {
  id: string;
  title: string;
  discountedPrice: number;
  windowEnd: string;
  heSlug?: string | null;
}

export async function loadData(
  db: DrizzleClient,
  config: Config,
  _ctx: LoadCtx,
): Promise<TickerDeal[] | null> {
  try {
    const now = new Date();
    const cutoff = new Date(now.getTime() + config.windowHours * 3_600_000);

    const rows = await db
      .select({
        id: deals.id,
        title: deals.title,
        discountedPrice: deals.minPrice,
        windowEnd: deals.windowEnd,
        heSlug: dealTranslations.slug,
      })
      .from(deals)
      .leftJoin(dealTranslations, and(
        eq(dealTranslations.dealId, deals.id),
        eq(dealTranslations.locale, 'he'),
      ))
      .where(
        and(
          eq(deals.dealState, 'ACTIVE'),
          isNotNull(deals.windowEnd),
          gt(deals.windowEnd, now),
          lt(deals.windowEnd, cutoff),
        ),
      )
      .orderBy(asc(deals.windowEnd))
      .limit(config.limit);

    if (rows.length === 0) return null;

    return rows.map((r) => ({
      id: r.id,
      title: r.title,
      discountedPrice: Number(r.discountedPrice),
      windowEnd: r.windowEnd!.toISOString(),
      heSlug: r.heSlug ?? undefined,
    }));
  } catch (err) {
    captureCaught(err, {
      scope: 'server.page-layout.modules.ticker-strip.loadData',
      severity: 'warning',
    });
    return null;
  }
}
