import { desc, eq } from 'drizzle-orm';
import { formatAgorotPlain, formatAgorotShekels } from '@/lib/money.js';
import { deals, order, orderLine, dealSkus } from '@/server/db/schema';
import { lineRedemptionStatusSql } from '@/server/fulfillment/voucher-line-state.js';
import type { KnowledgeAdapter, KnowledgeChunk } from './types';
import type { AdapterContext } from '@/server/support/types';

const LABEL = 'היסטוריית רכישות';

export const orderHistoryAdapter: KnowledgeAdapter = {
  id: 'order-history',
  label: LABEL,
  description: '10 הרכישות האחרונות של הפונה',
  async fetch(ctx: AdapterContext): Promise<KnowledgeChunk> {
    const base: KnowledgeChunk = {
      adapterId: 'order-history',
      label: LABEL,
      data: {},
      summary: '',
    };

    try {
      const rows = await ctx.db
        .select({
          id: orderLine.id,
          lineTotal: orderLine.lineTotal,
          orderStatus: order.status,
          createdAt: orderLine.createdAt,
          dealTitle: deals.title,
          redemptionStatus: lineRedemptionStatusSql(orderLine.id),
        })
        .from(orderLine)
        .innerJoin(order, eq(orderLine.orderId, order.id))
        .innerJoin(dealSkus, eq(orderLine.variantId, dealSkus.id))
        .innerJoin(deals, eq(dealSkus.dealId, deals.id))
        .where(eq(order.buyerUserId, ctx.userId))
        .orderBy(desc(orderLine.createdAt))
        .limit(10);

      const orders = rows.map((r) => ({
        id: r.id,
        dealTitle: r.dealTitle,
        amountPaid: formatAgorotPlain(Number(r.lineTotal)),
        paymentStatus: r.orderStatus,
        redemptionStatus: r.redemptionStatus ?? 'unredeemed',
        createdAt: r.createdAt.toISOString(),
      }));

      const totalAgorot = rows.reduce((sum, r) => sum + Number(r.lineTotal), 0);

      const summary =
        rows.length === 0
          ? 'אין רכישות קודמות'
          : `${rows.length} רכישות אחרונות, סה"כ ${formatAgorotShekels(totalAgorot)}`;

      return {
        ...base,
        data: { count: rows.length, totalAgorot, orders },
        summary,
      };
    } catch (err) {
      return { ...base, error: String(err) };
    }
  },
};
