import { and, gte, eq, sql } from 'drizzle-orm';
import type { DrizzleClient } from '@/server/db/client';
import { orderLine, order, dealSkus } from '@/server/db/schema';
import * as vendorQueries from '@/server/db/queries/vendors';
import type { LoadCtx } from '@/server/page-layout/types';
import type { Config } from './config';
import { captureCaught } from '@/server/observability/capture.server';

export interface GreetingData {
  displayName: string | null;
  monthlySavingsShekels: number | null;
}

export async function loadData(
  db: DrizzleClient,
  config: Config,
  ctx: LoadCtx,
): Promise<GreetingData | null> {
  try {
    if (!ctx.userId) return { displayName: null, monthlySavingsShekels: null };

    const now = new Date();
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);

    const vendorP = vendorQueries.getVendorByOwnerUser(db, ctx.userId, { locale: ctx.locale });

    // Savings = sum of (sku.originalPrice × qty - lineTotal/100) for each completed order line.
    // Join orderLine → dealSkus (price reference) + order (buyer + status filter).
    const savingsQ = config.showSavings
      ? db
          .select({
            total: sql<string>`COALESCE(SUM(${dealSkus.originalPrice}::numeric * ${orderLine.qty} - ${orderLine.lineTotal}::numeric / 100), 0)`,
          })
          .from(orderLine)
          .innerJoin(order, eq(order.id, orderLine.orderId))
          .innerJoin(dealSkus, eq(dealSkus.id, orderLine.variantId))
          .where(
            and(
              eq(order.buyerUserId, ctx.userId),
              eq(order.status, 'completed'),
              gte(orderLine.createdAt, monthStart),
            ),
          )
      : null;

    const [vendor, savingsResult] = await Promise.all([vendorP, savingsQ ?? Promise.resolve(null)]);

    const monthlySavingsShekels =
      config.showSavings && Array.isArray(savingsResult) && savingsResult[0]
        ? Number(savingsResult[0].total)
        : null;

    return {
      displayName: vendor?.displayName ?? null,
      monthlySavingsShekels,
    };
  } catch (err) {
    captureCaught(err, {
      scope: 'server.page-layout.modules.greeting-bar.loadData',
      severity: 'warning',
    });
    return null;
  }
}
