import { eq } from 'drizzle-orm';
import type { DrizzleClient } from '../client.js';
import * as schema from '../schema.js';
import { refreshDealCache } from '../../domain/variants/cache.js';
import { buildDefaultSkuRow } from '../../domain/variants/default-sku.js';

export type FulfillmentDemoDealSpec = {
  key: string;
  vendorId: string;
  categoryId: string;
  dealType: 'ITEM' | 'COUPON' | 'GROUP';
  titleHe: string;
  titleEn: string;
  descriptionHe: string;
  descriptionEn: string;
  isVoucher?: boolean;
  isPhysical?: boolean;
  specialInstructions?: string;
  pickupAddress?: string;
  pickupStart?: string;
  pickupEnd?: string;
  itemConfig?: Omit<typeof schema.dealItemConfig.$inferInsert, 'dealId'>;
  groupDeal?: Omit<typeof schema.groupDeals.$inferInsert, 'dealId'>;
  sku: {
    originalPrice: string;
    discountPercent: number;
    discountedPrice: string;
    quantityTotal: number;
  };
};

export async function insertFulfillmentDemoDealBundle(
  db: DrizzleClient,
  spec: FulfillmentDemoDealSpec,
  input: {
    imageUrl: string;
    windowStart: Date;
    windowEnd: Date;
    approvedAt: Date;
    slugFor: (title: string, dealId: string, locale: 'he' | 'en') => string;
  },
): Promise<string> {
  const [deal] = await db
    .insert(schema.deals)
    .values({
      vendorId: spec.vendorId,
      categoryId: spec.categoryId,
      dealType: spec.dealType,
      title: spec.titleHe,
      description: spec.descriptionHe,
      isVoucher: spec.isVoucher ?? false,
      isPhysical: spec.isPhysical ?? spec.dealType === 'ITEM',
      windowStart: input.windowStart,
      windowEnd: input.windowEnd,
      pickupStart: spec.pickupStart ?? null,
      pickupEnd: spec.pickupEnd ?? null,
      pickupAddress: spec.pickupAddress ?? '',
      specialInstructions: spec.specialInstructions ?? null,
      dealState: 'DRAFT',
      commissionRate: '0.100',
      translationStatus: 'COMPLETE',
      metadata: { source: 'fulfillment-demo', key: spec.key },
    })
    .returning({ id: schema.deals.id });

  if (!deal) throw new Error(`Failed to insert deal: ${spec.key}`);

  await db.insert(schema.dealSkus).values(buildDefaultSkuRow({ dealId: deal.id, ...spec.sku }));
  await refreshDealCache(db, deal.id);

  if (spec.itemConfig) {
    await db.insert(schema.dealItemConfig).values({ ...spec.itemConfig, dealId: deal.id });
  }

  if (spec.groupDeal) {
    await db.insert(schema.groupDeals).values({ ...spec.groupDeal, dealId: deal.id });
  }

  await db.insert(schema.dealImages).values({
    dealId: deal.id,
    url: input.imageUrl,
    isPrimary: true,
    sortOrder: 0,
    approvalStatus: 'APPROVED',
  });

  for (const locale of ['he', 'en'] as const) {
    const title = locale === 'he' ? spec.titleHe : spec.titleEn;
    const description = locale === 'he' ? spec.descriptionHe : spec.descriptionEn;
    await db.insert(schema.dealTranslations).values({
      dealId: deal.id,
      locale,
      slug: input.slugFor(title, deal.id, locale),
      title,
      description,
      pickupAddress: spec.pickupAddress ?? '',
      specialInstructions: spec.specialInstructions ?? null,
      status: 'OK',
      translatedAt: new Date(),
    });
  }

  await db
    .update(schema.deals)
    .set({
      dealState: 'ACTIVE',
      approvedAt: input.approvedAt,
      approvedBy: 'HUMAN',
    })
    .where(eq(schema.deals.id, deal.id));

  return deal.id;
}
