/**
 * Seed four fulfillment-demo deals (ITEM delivery/pickup, COUPON, GROUP) for checkout UX.
 * Run: DATABASE_URL=... tsx src/server/db/seeds/seed-fulfillment-demo.ts
 *
 * Idempotent — skips when any deal title contains the FFDEMO marker.
 */

import { scriptOutput } from '../../lib/script-output.js';
import { drizzle } from 'drizzle-orm/neon-serverless';
import { Pool, neonConfig } from '@neondatabase/serverless';
import ws from 'ws';
import { like } from 'drizzle-orm';
import { composedSchema } from '../schema-composed.js';
import {
  insertFulfillmentDemoDealBundle,
  type FulfillmentDemoDealSpec,
} from '../queries/seed-fulfillment-demo.js';
import { readSeedDatabaseUrl } from '../seed-cli-env.js';

neonConfig.webSocketConstructor = ws;

const DATABASE_URL = readSeedDatabaseUrl();

const pool = new Pool({ connectionString: DATABASE_URL });
const schema = composedSchema;
const db = drizzle(pool, { schema });

const MARKER = 'FFDEMO';

const VENDOR_TEST = 'bfcac0c0-d95f-473f-8f0a-a20716476972';
const VENDOR_GELATO = '26c14530-ad39-42fc-b735-03b134d00b9b';
const VENDOR_TEST_PICKUP_ADDRESS_ID = '892d80aa-1b74-4786-bb80-0f1c0e758839';

const FALLBACK_IMAGE_URL =
  'originals/700728cfdcc136035e5b204afb77a19aa54798c247caa1bd2339f43d5ddefd82.jpg';

const CATEGORY_BEVERAGE = '00000000-0000-0000-0000-000000000803';
const CATEGORY_BAKERY = '00000000-0000-0000-0000-000000000802';
const CATEGORY_MEAL = '00000000-0000-0000-0000-000000000801';
const CATEGORY_DESSERT = '00000000-0000-0000-0000-000000000804';

function daysAgo(n: number) {
  return new Date(Date.now() - n * 86_400_000);
}

function daysFromNow(n: number) {
  return new Date(Date.now() + n * 86_400_000);
}

function slugFor(title: string, dealId: string, locale: 'he' | 'en') {
  const base = title
    .replace(MARKER, '')
    .replace(/[|—]/g, ' ')
    .trim()
    .toLowerCase()
    .replace(/[^\p{L}\p{N}\s-]/gu, '')
    .replace(/\s+/g, '-')
    .slice(0, 40);
  const suffix = dealId.replace(/-/g, '').slice(0, 8);
  return locale === 'he' ? `${base || 'ffdemo'}-${suffix}` : `ffdemo-${base || 'deal'}-${suffix}`;
}

async function resolveFallbackImageUrl(): Promise<string> {
  const [row] = await db
    .select({ url: schema.dealImages.url })
    .from(schema.dealImages)
    .where(like(schema.dealImages.url, 'originals/%'))
    .limit(1);
  return row?.url ?? FALLBACK_IMAGE_URL;
}

type DealSeedSpec = FulfillmentDemoDealSpec;

async function insertDealBundle(
  spec: DealSeedSpec,
  imageUrl: string,
  windowStart: Date,
  windowEnd: Date,
) {
  return insertFulfillmentDemoDealBundle(db, spec, {
    imageUrl,
    windowStart,
    windowEnd,
    approvedAt: daysAgo(1),
    slugFor: slugFor,
  });
}

async function main() {
  const existing = await db
    .select({ id: schema.deals.id, title: schema.deals.title })
    .from(schema.deals)
    .where(like(schema.deals.title, `%${MARKER}%`))
    .limit(1);

  if (existing.length > 0) {
    scriptOutput(`FFDEMO deals already present (${existing[0]!.title}) — skipping`);
    await pool.end();
    return;
  }

  const imageUrl = await resolveFallbackImageUrl();
  scriptOutput(`Using fallback image URL: ${imageUrl}`);

  const windowStart = daysAgo(7);
  const windowEnd = daysFromNow(90);

  const specs: DealSeedSpec[] = [
    {
      key: 'item-delivery',
      vendorId: VENDOR_TEST,
      categoryId: CATEGORY_BEVERAGE,
      dealType: 'ITEM',
      titleHe: `${MARKER} | קפסולות קפה פרימיום למשלוח`,
      titleEn: `${MARKER} | Premium Coffee Capsules — Delivery`,
      descriptionHe:
        'מארז 40 קפסולות קפה איטלקי משובח, נשלח עד הבית תוך 3 ימי עסקים באמצעות שליח Wolt Drive.',
      descriptionEn:
        'Box of 40 premium Italian coffee capsules, delivered within 3 business days via Wolt Drive courier.',
      isPhysical: true,
      itemConfig: {
        handleSlaBusinessDays: 3,
        shippingMode: 'flat',
        shippingFlatAgorot: 1500,
        shippingFreeThresholdAgorot: null,
        pickupEnabled: false,
        pickupAddressId: null,
        returnWindowDays: 14,
        isReturnable: true,
        insuranceRequired: false,
        preferredCarrier: 'wolt_drive',
      },
      sku: {
        originalPrice: '120.00',
        discountPercent: 50,
        discountedPrice: '60.00',
        quantityTotal: 50,
      },
    },
    {
      key: 'item-pickup',
      vendorId: VENDOR_TEST,
      categoryId: CATEGORY_BAKERY,
      dealType: 'ITEM',
      titleHe: `${MARKER} | עוגת שוקולד לאיסוף עצמי`,
      titleEn: `${MARKER} | Chocolate Cake — Self Pickup`,
      descriptionHe:
        'עוגת שוקולד בלגית טרייה, מוכנה להזמנה מראש. איסוף עצמי מהסניף בתל אביב בשעות הפעילות.',
      descriptionEn:
        'Fresh Belgian chocolate cake, made to order. Self-pickup from our Tel Aviv branch during opening hours.',
      isPhysical: true,
      pickupAddress: 'שדרות רוטשילד 55, תל אביב',
      pickupStart: '09:00',
      pickupEnd: '18:00',
      itemConfig: {
        handleSlaBusinessDays: 2,
        shippingMode: 'pickup_only',
        shippingFlatAgorot: null,
        shippingFreeThresholdAgorot: null,
        pickupEnabled: true,
        pickupAddressId: VENDOR_TEST_PICKUP_ADDRESS_ID,
        pickupInstructions:
          'הציגו את אישור הרכישה בדלפק הקפה. העוגה תהיה מוכנה תוך שעתיים מההזמנה.',
        returnWindowDays: 14,
        isReturnable: false,
        insuranceRequired: false,
        preferredCarrier: 'pickup',
      },
      sku: {
        originalPrice: '95.00',
        discountPercent: 50,
        discountedPrice: '47.50',
        quantityTotal: 30,
      },
    },
    {
      key: 'coupon-voucher',
      vendorId: VENDOR_TEST,
      categoryId: CATEGORY_MEAL,
      dealType: 'COUPON',
      titleHe: `${MARKER} | שובר עיסוי 60 דקות`,
      titleEn: `${MARKER} | 60-Minute Massage Voucher`,
      descriptionHe:
        'שובר לעיסוי גוף מלא 60 דקות בספא רוטשילד 22. תקף לימים א׳-ה׳, בתיאום מראש בטלפון.',
      descriptionEn:
        'Voucher for a 60-minute full-body massage at Rothschild 22 Spa. Valid Sun–Thu, by phone appointment.',
      specialInstructions:
        'יש להתקשר לתיאום תור לפחות 48 שעות מראש. הציגו את קוד ה-QR בקבלה. לא ניתן לשימוש בערבי חג.',
      sku: {
        originalPrice: '350.00',
        discountPercent: 50,
        discountedPrice: '175.00',
        quantityTotal: 40,
      },
    },
    {
      key: 'group-voucher',
      vendorId: VENDOR_GELATO,
      categoryId: CATEGORY_DESSERT,
      dealType: 'GROUP',
      titleHe: `${MARKER} | גלידה משפחתית — מארז 4 כדורים`,
      titleEn: `${MARKER} | Family Gelato — 4 Scoops Pack`,
      descriptionHe:
        'מבצע קבוצתי לגלידה איטלקית: 4 כדורים לבחירה, וופל וקצפת. נפתח רק כשמתמלא מינימום משתתפים.',
      descriptionEn:
        'Group deal for Italian gelato: 4 scoops of your choice, waffle and whipped cream. Activates when minimum participants join.',
      specialInstructions:
        'השובר תקף לאיסוף מהגלידריה בלבד. יש להציג QR בדלפק. המבצע יופעל רק לאחר הגעה למינימום המשתתפים.',
      groupDeal: {
        fillRule: 'MINIMUM_THRESHOLD',
        minGroupSize: 5,
        maxGroupSize: 20,
        perCustomerLimit: 1,
        cancellationPolicy: 'LEGAL_ONLY',
        tieredPricingEnabled: false,
        earlyBirdEnabled: false,
        groupState: 'COLLECTING',
        currentReservationCount: 0,
      },
      sku: {
        originalPrice: '80.00',
        discountPercent: 50,
        discountedPrice: '40.00',
        quantityTotal: 60,
      },
    },
  ];

  const created: Array<{ key: string; id: string; slugHe: string }> = [];

  for (const spec of specs) {
    const id = await insertDealBundle(spec, imageUrl, windowStart, windowEnd);
    const slugHe = slugFor(spec.titleHe, id, 'he');
    created.push({ key: spec.key, id, slugHe });
    scriptOutput(`Created ${spec.key}: ${id} (/${slugHe})`);
  }

  scriptOutput('\nFFDEMO seed complete:');
  for (const row of created) {
    scriptOutput(`  ${row.key}: id=${row.id} slug=${row.slugHe}`);
  }

  await pool.end();
}

main().catch((err) => {
  console.error('seed-fulfillment-demo failed:', err);
  process.exit(1);
});
