import 'dotenv/config';
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
import { BRAND, VOCAB } from '@/lib/white-label/constants';

const prisma = new PrismaClient();

async function main() {
  console.log('🌱 Seeding ERP demo data...');

  // =============
  // GFS ADMIN USER
  // =============
  console.log('👤 Creating GFS Admin User...');
  
  const adminPassword = await bcrypt.hash('Majestic12', 12);
  
  await prisma.gfsUser.upsert({
    where: { email: 'admin@ghostfoundry.ai' },
    update: {
      passwordHash: adminPassword,
      status: 'active',
    },
    create: {
      email: 'admin@ghostfoundry.ai',
      name: 'Scott (Admin)',
      passwordHash: adminPassword,
      status: 'active',
      department: 'Executive',
      title: 'Founder & CEO',
      timezone: 'America/Chicago',
    },
  });
  
  console.log('✅ GFS Admin user created: admin@ghostfoundry.ai / Majestic12');

  // =============
  // DARK FACTORY DEMO USER
  // =============
  console.log('🏭 Creating The Hearth Demo User...');
  
  const dfDemoPassword = await bcrypt.hash('DarkFactory2026!', 12);
  
  await prisma.gfsUser.upsert({
    where: { email: 'demo@darkfactory.ai' },
    update: {
      passwordHash: dfDemoPassword,
      status: 'active',
    },
    create: {
      email: 'demo@darkfactory.ai',
      name: 'The Hearth Demo',
      passwordHash: dfDemoPassword,
      status: 'active',
      department: 'Engineering',
      title: 'Demo User',
    },
  });
  
  console.log('✅ The Hearth demo user created: demo@darkfactory.ai / DarkFactory2026!');

  // Clean existing demo data
  await prisma.transaction.deleteMany({});
  await prisma.budget.deleteMany({});
  await prisma.invoice.deleteMany({});
  await prisma.account.deleteMany({});
  await prisma.payrollRecord.deleteMany({});
  await prisma.leaveRequest.deleteMany({});
  await prisma.timeEntry.deleteMany({});
  await prisma.employee.deleteMany({});
  await prisma.department.deleteMany({});
  await prisma.stockMovement.deleteMany({});
  await prisma.purchaseOrderItem.deleteMany({});
  await prisma.purchaseOrder.deleteMany({});
  await prisma.inventoryItem.deleteMany({});
  await prisma.product.deleteMany({});
  await prisma.supplier.deleteMany({});
  await prisma.contract.deleteMany({});
  await prisma.document.deleteMany({});

  // =============
  // FINANCE DATA
  // =============
  console.log('💰 Creating Finance data...');

  const accounts = await Promise.all([
    prisma.account.create({
      data: { code: '1000', name: 'Cash', type: 'asset', category: 'cash', balance: 125000 },
    }),
    prisma.account.create({
      data: { code: '1100', name: 'Accounts Receivable', type: 'asset', category: 'receivable', balance: 47200 },
    }),
    prisma.account.create({
      data: { code: '1200', name: 'Inventory', type: 'asset', category: 'inventory', balance: 85000 },
    }),
    prisma.account.create({
      data: { code: '2000', name: 'Accounts Payable', type: 'liability', category: 'payable', balance: 32000 },
    }),
    prisma.account.create({
      data: { code: '3000', name: 'Owner Equity', type: 'equity', category: 'equity', balance: 200000 },
    }),
    prisma.account.create({
      data: { code: '4000', name: 'Sales Revenue', type: 'revenue', category: 'revenue', balance: 175000 },
    }),
    prisma.account.create({
      data: { code: '5000', name: 'Operating Expenses', type: 'expense', category: 'expense', balance: 48000 },
    }),
    prisma.account.create({
      data: { code: '5100', name: 'Payroll Expenses', type: 'expense', category: 'expense', balance: 62000 },
    }),
  ]);

  const cashAccount = accounts.find(a => a.code === '1000')!;
  const arAccount = accounts.find(a => a.code === '1100')!;

  // Transactions
  await Promise.all([
    prisma.transaction.create({
      data: {
        accountId: cashAccount.id,
        type: 'receipt',
        description: 'Customer Payment - Invoice #1042',
        amount: 5500,
        status: 'posted',
        date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
      },
    }),
    prisma.transaction.create({
      data: {
        accountId: cashAccount.id,
        type: 'payment',
        description: 'Vendor Payment - Office Supplies',
        amount: -1200,
        status: 'posted',
        date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
      },
    }),
    prisma.transaction.create({
      data: {
        accountId: arAccount.id,
        type: 'journal',
        description: 'Invoice #1050 Issued',
        amount: 8500,
        status: 'posted',
      },
    }),
  ]);

  // Invoices
  await Promise.all([
    prisma.invoice.create({
      data: {
        invoiceNumber: 'INV-1050',
        type: 'customer',
        customerId: 'acme-corp',
        issueDate: new Date(),
        dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        status: 'sent',
        subtotal: 8000,
        tax: 500,
        total: 8500,
        items: [{ description: 'Consulting Services', qty: 40, rate: 200, amount: 8000 }],
      },
    }),
    prisma.invoice.create({
      data: {
        invoiceNumber: 'INV-1048',
        type: 'customer',
        customerId: 'beta-inc',
        issueDate: new Date(Date.now() - 45 * 24 * 60 * 60 * 1000),
        dueDate: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
        status: 'overdue',
        subtotal: 3200,
        tax: 200,
        total: 3400,
        amountPaid: 0,
        items: [{ description: 'Software License', qty: 1, rate: 3200, amount: 3200 }],
      },
    }),
  ]);

  // =============
  // HR DATA
  // =============
  console.log('👥 Creating HR data...');

  const departments = await Promise.all([
    prisma.department.create({
      data: { name: 'Engineering', code: 'ENG', description: 'Software Engineering Team', headCount: 8 },
    }),
    prisma.department.create({
      data: { name: 'Operations', code: 'OPS', description: 'Business Operations', headCount: 5 },
    }),
    prisma.department.create({
      data: { name: 'Sales', code: 'SLS', description: 'Sales and Business Development', headCount: 6 },
    }),
    prisma.department.create({
      data: { name: 'Marketing', code: 'MKT', description: 'Marketing and Growth', headCount: 4 },
    }),
  ]);

  const engDept = departments.find(d => d.code === 'ENG')!;
  const opsDept = departments.find(d => d.code === 'OPS')!;
  const slsDept = departments.find(d => d.code === 'SLS')!;

  const employees = await Promise.all([
    prisma.employee.create({
      data: {
        employeeId: 'EMP001',
        firstName: 'Sarah',
        lastName: 'Chen',
        email: 'sarah.chen@ghostfoundry.ai',
        departmentId: engDept.id,
        title: 'Senior Engineer',
        employmentType: 'full-time',
        salary: 145000,
        startDate: new Date('2023-03-15'),
      },
    }),
    prisma.employee.create({
      data: {
        employeeId: 'EMP002',
        firstName: 'Marcus',
        lastName: 'Johnson',
        email: 'marcus.johnson@ghostfoundry.ai',
        departmentId: opsDept.id,
        title: 'Operations Manager',
        employmentType: 'full-time',
        salary: 95000,
        startDate: new Date('2023-06-01'),
      },
    }),
    prisma.employee.create({
      data: {
        employeeId: 'EMP003',
        firstName: 'Emily',
        lastName: 'Rodriguez',
        email: 'emily.rodriguez@ghostfoundry.ai',
        departmentId: slsDept.id,
        title: 'Account Executive',
        employmentType: 'full-time',
        salary: 85000,
        startDate: new Date('2024-01-10'),
      },
    }),
    prisma.employee.create({
      data: {
        employeeId: 'EMP004',
        firstName: 'Alex',
        lastName: 'Kim',
        email: 'alex.kim@ghostfoundry.ai',
        departmentId: engDept.id,
        title: 'Frontend Developer',
        employmentType: 'contractor',
        salary: 120000,
        startDate: new Date('2024-02-01'),
      },
    }),
  ]);

  // Leave requests
  await Promise.all([
    prisma.leaveRequest.create({
      data: {
        employeeId: employees[0].id,
        type: 'vacation',
        startDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
        endDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
        days: 5,
        reason: 'Family vacation',
        status: 'pending',
      },
    }),
    prisma.leaveRequest.create({
      data: {
        employeeId: employees[2].id,
        type: 'sick',
        startDate: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
        endDate: new Date(Date.now() + 4 * 24 * 60 * 60 * 1000),
        days: 2,
        reason: 'Medical appointment',
        status: 'pending',
      },
    }),
  ]);

  // =============
  // INVENTORY DATA
  // =============
  console.log('📦 Creating Inventory data...');

  const suppliers = await Promise.all([
    prisma.supplier.create({
      data: {
        name: 'TechParts Global',
        code: 'SUP001',
        contactName: 'John Smith',
        email: 'john@techparts.com',
        paymentTerms: 'Net 30',
        rating: 4.5,
      },
    }),
    prisma.supplier.create({
      data: {
        name: 'Office Essentials',
        code: 'SUP002',
        contactName: 'Lisa Wang',
        email: 'lisa@officeessentials.com',
        paymentTerms: 'Net 15',
        rating: 4.2,
      },
    }),
  ]);

  const products = await Promise.all([
    prisma.product.create({
      data: {
        sku: 'LAPTOP-001',
        name: 'Developer Laptop',
        description: 'High-performance laptop for development',
        category: 'Electronics',
        supplierId: suppliers[0].id,
        costPrice: 1200,
        salePrice: 1599,
        reorderLevel: 5,
        reorderQuantity: 10,
      },
    }),
    prisma.product.create({
      data: {
        sku: 'MONITOR-001',
        name: '4K Monitor',
        description: '32-inch 4K display',
        category: 'Electronics',
        supplierId: suppliers[0].id,
        costPrice: 350,
        salePrice: 499,
        reorderLevel: 10,
        reorderQuantity: 20,
      },
    }),
    prisma.product.create({
      data: {
        sku: 'DESK-001',
        name: 'Standing Desk',
        description: 'Electric adjustable standing desk',
        category: 'Furniture',
        supplierId: suppliers[1].id,
        costPrice: 400,
        salePrice: 649,
        reorderLevel: 3,
        reorderQuantity: 5,
      },
    }),
    prisma.product.create({
      data: {
        sku: 'CHAIR-001',
        name: 'Ergonomic Chair',
        description: 'Premium ergonomic office chair',
        category: 'Furniture',
        supplierId: suppliers[1].id,
        costPrice: 280,
        salePrice: 449,
        reorderLevel: 5,
        reorderQuantity: 10,
      },
    }),
  ]);

  // Create inventory items
  await Promise.all([
    prisma.inventoryItem.create({
      data: {
        productId: products[0].id,
        quantity: 12,
        availableQty: 10,
        reservedQty: 2,
        status: 'in-stock',
      },
    }),
    prisma.inventoryItem.create({
      data: {
        productId: products[1].id,
        quantity: 8,
        availableQty: 8,
        status: 'low-stock',
      },
    }),
    prisma.inventoryItem.create({
      data: {
        productId: products[2].id,
        quantity: 2,
        availableQty: 2,
        status: 'low-stock',
      },
    }),
    prisma.inventoryItem.create({
      data: {
        productId: products[3].id,
        quantity: 0,
        availableQty: 0,
        status: 'out-of-stock',
      },
    }),
  ]);

  // Stock movements
  await Promise.all([
    prisma.stockMovement.create({
      data: {
        productId: products[0].id,
        type: 'in',
        quantity: 15,
        reference: 'PO-001',
        reason: 'Purchase Order Received',
      },
    }),
    prisma.stockMovement.create({
      data: {
        productId: products[0].id,
        type: 'out',
        quantity: 3,
        reference: 'SO-1001',
        reason: 'Customer Order',
      },
    }),
    prisma.stockMovement.create({
      data: {
        productId: products[1].id,
        type: 'in',
        quantity: 20,
        reference: 'PO-002',
        reason: 'Purchase Order Received',
      },
    }),
  ]);

  // GFS Platform Products (upsert to avoid duplicates)
  const gfsProductData = [
    { sku: 'GFS-SEC-001', name: 'Familiar Shield Security Suite', description: 'Enterprise-grade AI-powered security monitoring and threat detection', category: 'Security', unit: 'license', costPrice: 189, salePrice: 299, reorderLevel: 5, reorderQuantity: 25, leadTimeDays: 1 },
    { sku: 'GFS-ANA-001', name: 'Familiars Analytics Platform', description: 'Real-time business intelligence and predictive analytics engine', category: 'Analytics', unit: 'license', costPrice: 249, salePrice: 399, reorderLevel: 5, reorderQuantity: 25, leadTimeDays: 1 },
    { sku: 'GFS-AUT-001', name: 'The Hearth Automation Module', description: 'Autonomous workflow automation with AI agent orchestration', category: 'Automation', unit: 'license', costPrice: 349, salePrice: 549, reorderLevel: 3, reorderQuantity: 15, leadTimeDays: 1 },
    { sku: 'GFS-INT-001', name: 'Foundry Integration Hub', description: 'Universal connector for CRM, ERP, and cloud service integration', category: 'Integration', unit: 'license', costPrice: 129, salePrice: 199, reorderLevel: 10, reorderQuantity: 50, leadTimeDays: 1 },
    { sku: 'GFS-CMP-001', name: 'Compliance Wisp Package', description: 'Automated compliance monitoring with audit trail and reporting', category: 'Compliance', unit: 'license', costPrice: 199, salePrice: 349, reorderLevel: 5, reorderQuantity: 20, leadTimeDays: 1 },
    { sku: 'GFS-SUP-001', name: 'Premium Support & SLA', description: '24/7 dedicated support with <1hr response SLA and priority escalation', category: 'Support', unit: 'subscription', costPrice: 99, salePrice: 149, reorderLevel: 100, reorderQuantity: 500, leadTimeDays: 0 },
  ];
  for (const gfsProd of gfsProductData) {
    const existing = await prisma.product.findUnique({ where: { sku: gfsProd.sku } });
    if (!existing) {
      const created = await prisma.product.create({ data: gfsProd });
      await prisma.inventoryItem.create({ data: { productId: created.id, quantity: 100, availableQty: 100, status: 'in-stock', location: 'main-warehouse' } });
      console.log('  Created GFS product:', gfsProd.sku);
    }
  }

  // Purchase orders
  const po = await prisma.purchaseOrder.create({
    data: {
      orderNumber: 'PO-003',
      supplierId: suppliers[1].id,
      status: 'confirmed',
      expectedDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
      subtotal: 2800,
      tax: 224,
      total: 3024,
    },
  });

  await prisma.purchaseOrderItem.create({
    data: {
      purchaseOrderId: po.id,
      productId: products[3].id,
      quantity: 10,
      unitPrice: 280,
      total: 2800,
    },
  });

  // =============
  // DOCUMENTS DATA
  // =============
  console.log('📄 Creating Documents data...');

  await Promise.all([
    prisma.document.create({
      data: {
        title: 'Employee Handbook 2024',
        type: 'policy',
        category: 'HR',
        description: 'Company policies and procedures',
        fileSize: 2456789,
        mimeType: 'application/pdf',
        status: 'active',
        tags: ['hr', 'policy', 'handbook'],
      },
    }),
    prisma.document.create({
      data: {
        title: 'Q1 Financial Report',
        type: 'report',
        category: 'Finance',
        description: 'Quarterly financial summary',
        fileSize: 1234567,
        mimeType: 'application/pdf',
        status: 'active',
        tags: ['finance', 'quarterly', 'report'],
      },
    }),
    prisma.document.create({
      data: {
        title: 'Security Compliance Audit',
        type: 'report',
        category: 'Compliance',
        description: 'Annual security compliance documentation',
        fileSize: 3567890,
        mimeType: 'application/pdf',
        status: 'active',
        tags: ['security', 'compliance', 'audit'],
      },
    }),
  ]);

  // Contracts
  await Promise.all([
    prisma.contract.create({
      data: {
        contractNumber: 'CTR-2024-001',
        title: 'Enterprise Software License',
        type: 'vendor',
        partyName: 'CloudTech Solutions',
        partyType: 'vendor',
        startDate: new Date('2024-01-01'),
        endDate: new Date(Date.now() + 25 * 24 * 60 * 60 * 1000), // Expiring in 25 days
        value: 50000,
        status: 'active',
        autoRenew: true,
      },
    }),
    prisma.contract.create({
      data: {
        contractNumber: 'CTR-2024-002',
        title: 'Office Lease Agreement',
        type: 'vendor',
        partyName: 'Premier Properties',
        partyType: 'vendor',
        startDate: new Date('2023-06-01'),
        endDate: new Date('2026-05-31'),
        value: 180000,
        status: 'active',
        autoRenew: false,
      },
    }),
    prisma.contract.create({
      data: {
        contractNumber: 'CTR-2024-003',
        title: 'Annual Support Agreement',
        type: 'customer',
        partyName: 'Acme Corporation',
        partyType: 'customer',
        startDate: new Date('2024-03-01'),
        endDate: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000), // Expiring in 15 days
        value: 24000,
        status: 'active',
        autoRenew: true,
      },
    }),
  ]);

  // Create a budget
  await prisma.budget.create({
    data: {
      name: 'Q1 Operations Budget',
      departmentId: opsDept.id,
      period: 'quarterly',
      startDate: new Date('2024-01-01'),
      endDate: new Date('2024-03-31'),
      amount: 75000,
      spent: 48500,
      remaining: 26500,
      status: 'active',
    },
  });

  // =============
  // CRM DATA
  // =============
  console.log('🤝 Creating CRM data...');

  // Clean CRM data first
  await prisma.salesOrderItem.deleteMany({});
  await prisma.salesOrder.deleteMany({});
  await prisma.quoteItem.deleteMany({});
  await prisma.quote.deleteMany({});
  await prisma.lead.deleteMany({});
  await prisma.opportunity.deleteMany({});
  await prisma.contact.deleteMany({});
  await prisma.customer.deleteMany({});

  // Create customers
  const customers = await Promise.all([
    prisma.customer.create({
      data: {
        customerNumber: 'CUST-00001',
        name: 'Acme Corporation',
        type: 'company',
        industry: 'Technology',
        email: 'procurement@acme.com',
        phone: '555-0100',
        website: 'https://acme.com',
        paymentTerms: 'Net 30',
        creditLimit: 100000,
        status: 'active',
      },
    }),
    prisma.customer.create({
      data: {
        customerNumber: 'CUST-00002',
        name: 'TechStart Inc',
        type: 'company',
        industry: 'Software',
        email: 'orders@techstart.io',
        phone: '555-0200',
        paymentTerms: 'Net 15',
        creditLimit: 50000,
        status: 'active',
      },
    }),
    prisma.customer.create({
      data: {
        customerNumber: 'CUST-00003',
        name: 'Global Retail Partners',
        type: 'company',
        industry: 'Retail',
        email: 'buyer@globalretail.com',
        phone: '555-0300',
        paymentTerms: 'Net 45',
        creditLimit: 250000,
        status: 'active',
      },
    }),
  ]);

  // Create contacts
  await Promise.all([
    prisma.contact.create({
      data: {
        customerId: customers[0].id,
        firstName: 'Sarah',
        lastName: 'Johnson',
        email: 'sarah.johnson@acme.com',
        phone: '555-0101',
        title: 'Procurement Manager',
        isPrimary: true,
      },
    }),
    prisma.contact.create({
      data: {
        customerId: customers[1].id,
        firstName: 'Mike',
        lastName: 'Chen',
        email: 'mike@techstart.io',
        phone: '555-0201',
        title: 'CEO',
        isPrimary: true,
      },
    }),
    prisma.contact.create({
      data: {
        customerId: customers[2].id,
        firstName: 'Lisa',
        lastName: 'Rodriguez',
        email: 'lisa.r@globalretail.com',
        phone: '555-0301',
        title: 'VP of Operations',
        isPrimary: true,
      },
    }),
  ]);

  // Create leads
  await Promise.all([
    prisma.lead.create({
      data: {
        companyName: 'Innovative Labs',
        contactName: 'David Park',
        email: 'david@innovativelabs.co',
        phone: '555-0400',
        source: 'website',
        status: 'qualified',
        rating: 'hot',
        industry: 'Biotech',
        estimatedValue: 75000,
      },
    }),
    prisma.lead.create({
      data: {
        companyName: 'Metro Services LLC',
        contactName: 'Amanda White',
        email: 'amanda@metroservices.com',
        phone: '555-0500',
        source: 'referral',
        status: 'contacted',
        rating: 'warm',
        industry: 'Services',
        estimatedValue: 35000,
      },
    }),
    prisma.lead.create({
      data: {
        companyName: 'CloudFirst Solutions',
        contactName: 'James Turner',
        email: 'jturner@cloudfirst.com',
        source: 'cold-call',
        status: 'new',
        rating: 'cold',
        industry: 'Cloud Computing',
        estimatedValue: 120000,
      },
    }),
  ]);

  // Create opportunities
  const opportunities = await Promise.all([
    prisma.opportunity.create({
      data: {
        name: 'Acme Q2 Expansion',
        customerId: customers[0].id,
        stage: 'proposal',
        probability: 60,
        expectedValue: 85000,
        expectedClose: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        description: 'Q2 infrastructure expansion project',
        nextStep: 'Schedule demo with technical team',
      },
    }),
    prisma.opportunity.create({
      data: {
        name: 'TechStart Platform Integration',
        customerId: customers[1].id,
        stage: 'negotiation',
        probability: 80,
        expectedValue: 45000,
        expectedClose: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
        description: 'Full platform integration project',
        nextStep: 'Final contract review',
      },
    }),
    prisma.opportunity.create({
      data: {
        name: 'Global Retail POS Rollout',
        customerId: customers[2].id,
        stage: 'qualification',
        probability: 30,
        expectedValue: 200000,
        expectedClose: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
        description: 'Multi-location POS system rollout',
        nextStep: 'Requirements gathering meeting',
      },
    }),
  ]);

  // Create quotes
  const quote1 = await prisma.quote.create({
    data: {
      quoteNumber: 'QT-00001',
      customerId: customers[0].id,
      opportunityId: opportunities[0].id,
      status: 'sent',
      validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      subtotal: 85000,
      discount: 5,
      discountType: 'percentage',
      tax: 6800,
      total: 87550,
      terms: 'Net 30. Delivery within 4 weeks of acceptance.',
    },
  });

  await prisma.quoteItem.createMany({
    data: [
      { quoteId: quote1.id, description: 'Enterprise License (Annual)', quantity: 1, unitPrice: 50000, total: 50000, sortOrder: 0 },
      { quoteId: quote1.id, description: 'Implementation Services', quantity: 80, unitPrice: 250, total: 20000, sortOrder: 1 },
      { quoteId: quote1.id, description: 'Training Package', quantity: 1, unitPrice: 15000, total: 15000, sortOrder: 2 },
    ],
  });

  // Create sales orders
  const order1 = await prisma.salesOrder.create({
    data: {
      orderNumber: 'SO-00001',
      customerId: customers[1].id,
      status: 'processing',
      orderDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
      requiredDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
      subtotal: 32000,
      tax: 2560,
      shipping: 500,
      total: 35060,
      paymentStatus: 'partial',
      paymentMethod: 'wire',
      notes: 'Priority order - expedite shipping',
    },
  });

  await prisma.salesOrderItem.createMany({
    data: [
      { salesOrderId: order1.id, description: 'Professional License', quantity: 10, unitPrice: 2500, total: 25000, sortOrder: 0 },
      { salesOrderId: order1.id, description: 'Support Package (12 mo)', quantity: 1, unitPrice: 7000, total: 7000, sortOrder: 1 },
    ],
  });

  // ============================================
  // MODULE CONFIGURATION & AGENT HIERARCHY SEED
  // ============================================
  console.log('🔧 Syncing module registry...');
  const { MODULE_REGISTRY } = await import('../lib/modules/registry');
  for (const mod of MODULE_REGISTRY) {
    await prisma.moduleConfig.upsert({
      where: { moduleId: mod.moduleId },
      create: {
        moduleId: mod.moduleId,
        name: mod.name,
        description: mod.description,
        category: mod.category,
        icon: mod.icon,
        isEnabled: mod.defaultEnabled || mod.isCore,
        isCore: mod.isCore,
        sortOrder: mod.sortOrder,
        dependencies: mod.dependencies,
        metadata: { features: mod.features, tier: mod.tier, agentId: mod.agentId || null },
        enabledAt: (mod.defaultEnabled || mod.isCore) ? new Date() : null,
      },
      update: {
        name: mod.name,
        description: mod.description,
        category: mod.category,
        icon: mod.icon,
        isCore: mod.isCore,
        sortOrder: mod.sortOrder,
        dependencies: mod.dependencies,
        metadata: { features: mod.features, tier: mod.tier, agentId: mod.agentId || null },
      },
    });
  }

  console.log('🧠 Initializing agent hierarchy...');
  const { AGENT_DEFINITIONS } = await import('../lib/agent-hierarchy/agents');
  for (const def of AGENT_DEFINITIONS) {
    await prisma.domainAgent.upsert({
      where: { agentId: def.agentId },
      create: {
        agentId: def.agentId,
        name: def.name,
        title: def.title,
        domain: def.domain,
        personality: def.personality,
        systemPrompt: def.systemPrompt,
        parentAgentId: def.parentAgentId,
        moduleId: def.moduleId,
        avatarColor: def.avatarColor,
        capabilities: def.capabilities,
        status: 'active',
        config: { escalationTriggers: def.escalationTriggers },
      },
      update: {
        name: def.name,
        title: def.title,
        personality: def.personality,
        systemPrompt: def.systemPrompt,
        avatarColor: def.avatarColor,
        capabilities: def.capabilities,
        config: { escalationTriggers: def.escalationTriggers },
      },
    });
  }

  // =============
  // SWAG STORE PRODUCTS
  // =============
  console.log('👕 Seeding Swag Store products...');

  // Clear existing swag data
  await prisma.swagOrderItem.deleteMany({});
  await prisma.swagOrder.deleteMany({});
  await prisma.swagCartItem.deleteMany({});
  await prisma.swagCart.deleteMany({});
  await prisma.swagVariant.deleteMany({});
  await prisma.swagProduct.deleteMany({});

  const swagProducts = [
    {
      sku: 'GFS-HOODIE-001',
      name: `${BRAND.primaryName} Classic Hoodie`,
      description: `Premium heavyweight cotton blend hoodie with embroidered ${BRAND.companyName} logo. Features a ghost icon on chest and "The Familiars Watch Over You" on back.`,
      category: 'hoodies',
      basePrice: 79.99,
      imageUrl: 'https://cdn.abacus.ai/images/a5031541-b9d6-44b5-928b-ee1bff7fa04f.png',
      variants: [
        { size: 'S', color: 'Black', stock: 25 },
        { size: 'M', color: 'Black', stock: 40 },
        { size: 'L', color: 'Black', stock: 50 },
        { size: 'XL', color: 'Black', stock: 35 },
        { size: '2XL', color: 'Black', stock: 20 },
        { size: 'S', color: 'Navy', stock: 20 },
        { size: 'M', color: 'Navy', stock: 30 },
        { size: 'L', color: 'Navy', stock: 40 },
        { size: 'XL', color: 'Navy', stock: 25 },
        { size: '2XL', color: 'Navy', stock: 15 },
      ],
    },
    {
      sku: 'GFS-HOODIE-002',
      name: 'Familiar Spirit Hoodie',
      description: 'Tech-inspired zip-up hoodie with reflective ghost logo and hidden headphone cord loops. Perfect for late-night debugging sessions.',
      category: 'hoodies',
      basePrice: 89.99,
      imageUrl: 'https://cdn.abacus.ai/images/d727341d-3f96-4438-b898-12b8604416cd.png',
      variants: [
        { size: 'S', color: 'Charcoal', stock: 20 },
        { size: 'M', color: 'Charcoal', stock: 35 },
        { size: 'L', color: 'Charcoal', stock: 45 },
        { size: 'XL', color: 'Charcoal', stock: 30 },
        { size: '2XL', color: 'Charcoal', stock: 15 },
      ],
    },
    {
      sku: 'GFS-TSHIRT-001',
      name: 'Familiar Spirit Tee',
      description: 'Lightweight performance t-shirt with moisture-wicking fabric. Features subtle ghost watermark and "AI-Native Operations" tagline.',
      category: 'tshirts',
      basePrice: 34.99,
      imageUrl: 'https://cdn.abacus.ai/images/6ddc8bcc-6f25-44cf-9fbc-1ed2c82e3ce7.png',
      variants: [
        { size: 'XS', color: 'Black', stock: 15 },
        { size: 'S', color: 'Black', stock: 30 },
        { size: 'M', color: 'Black', stock: 50 },
        { size: 'L', color: 'Black', stock: 60 },
        { size: 'XL', color: 'Black', stock: 40 },
        { size: '2XL', color: 'Black', stock: 20 },
        { size: 'XS', color: 'White', stock: 10 },
        { size: 'S', color: 'White', stock: 25 },
        { size: 'M', color: 'White', stock: 40 },
        { size: 'L', color: 'White', stock: 50 },
        { size: 'XL', color: 'White', stock: 30 },
        { size: '2XL', color: 'White', stock: 15 },
      ],
    },
    {
      sku: 'GFS-TSHIRT-002',
      name: 'The Ghost Remembers Tee',
      description: 'Bold statement tee with large ghost icon and "The Ghost Remembers" text. 100% organic cotton.',
      category: 'tshirts',
      basePrice: 29.99,
      imageUrl: 'https://cdn.abacus.ai/images/1c337ddb-2411-41f8-ae6c-e86a6c842772.png',
      variants: [
        { size: 'S', color: 'Midnight Blue', stock: 25 },
        { size: 'M', color: 'Midnight Blue', stock: 40 },
        { size: 'L', color: 'Midnight Blue', stock: 50 },
        { size: 'XL', color: 'Midnight Blue', stock: 35 },
        { size: '2XL', color: 'Midnight Blue', stock: 20 },
      ],
    },
    {
      sku: 'GFS-SHIRT-001',
      name: 'Executive Operations Polo',
      description: 'Premium polo shirt with embroidered ghost logo. Professional enough for investor meetings, cool enough for the team.',
      category: 'shirts',
      basePrice: 54.99,
      imageUrl: 'https://cdn.abacus.ai/images/0522f591-b1d7-481c-a15f-19315b88fb42.png',
      variants: [
        { size: 'S', color: 'Black', stock: 15 },
        { size: 'M', color: 'Black', stock: 25 },
        { size: 'L', color: 'Black', stock: 35 },
        { size: 'XL', color: 'Black', stock: 25 },
        { size: 'S', color: 'Slate Gray', stock: 15 },
        { size: 'M', color: 'Slate Gray', stock: 25 },
        { size: 'L', color: 'Slate Gray', stock: 30 },
        { size: 'XL', color: 'Slate Gray', stock: 20 },
      ],
    },
    {
      sku: 'GFS-HAT-001',
      name: 'Ghost Operator Snapback',
      description: 'Classic snapback cap with embroidered ghost icon and flat brim. One size fits most.',
      category: 'hats',
      basePrice: 29.99,
      imageUrl: 'https://cdn.abacus.ai/images/4c4b926b-ffbe-4f8c-b52f-dd9d1c12d561.png',
      variants: [
        { size: 'One Size', color: 'Black', stock: 60 },
        { size: 'One Size', color: 'Navy', stock: 40 },
        { size: 'One Size', color: 'Gray', stock: 35 },
      ],
    },
    {
      sku: 'GFS-HAT-002',
      name: 'Familiar Spirit Hat',
      description: 'Relaxed fit dad hat with subtle ghost embroidery. Adjustable strap for perfect fit.',
      category: 'hats',
      basePrice: 24.99,
      imageUrl: 'https://cdn.abacus.ai/images/75cdd4a7-7597-4eac-9fad-99b69896e96c.png',
      variants: [
        { size: 'One Size', color: 'Black', stock: 45 },
        { size: 'One Size', color: 'White', stock: 30 },
        { size: 'One Size', color: 'Olive', stock: 25 },
      ],
    },
    {
      sku: 'GFS-COAT-001',
      name: 'Familiars Bomber Jacket',
      description: 'Premium bomber jacket with satin lining. Features large ghost embroidery on back and small logo on chest. Water-resistant.',
      category: 'coats',
      basePrice: 149.99,
      imageUrl: 'https://cdn.abacus.ai/images/ad128653-bf33-4fdc-a53a-371ace84cde2.png',
      variants: [
        { size: 'S', color: 'Black', stock: 10 },
        { size: 'M', color: 'Black', stock: 15 },
        { size: 'L', color: 'Black', stock: 20 },
        { size: 'XL', color: 'Black', stock: 15 },
        { size: '2XL', color: 'Black', stock: 8 },
      ],
    },
    {
      sku: 'GFS-COAT-002',
      name: 'Ghost Operations Windbreaker',
      description: 'Lightweight windbreaker with packable hood. Reflective ghost logo for visibility. Perfect for outdoor ops.',
      category: 'coats',
      basePrice: 89.99,
      imageUrl: 'https://cdn.abacus.ai/images/42d13898-6217-4c8b-a285-f3d09c77f3cc.png',
      variants: [
        { size: 'S', color: 'Black/Cyan', stock: 15 },
        { size: 'M', color: 'Black/Cyan', stock: 25 },
        { size: 'L', color: 'Black/Cyan', stock: 30 },
        { size: 'XL', color: 'Black/Cyan', stock: 20 },
        { size: '2XL', color: 'Black/Cyan', stock: 10 },
      ],
    },
    {
      sku: 'GFS-COAT-003',
      name: 'Enterprise Softshell',
      description: 'Technical softshell jacket with 4-way stretch. Subtle ghost logo, zippered pockets. Enterprise-grade comfort.',
      category: 'coats',
      basePrice: 119.99,
      imageUrl: 'https://cdn.abacus.ai/images/f2d1c3c1-47cb-4b9d-b06f-6d1bcbfbf7cc.png',
      variants: [
        { size: 'S', color: 'Charcoal', stock: 12 },
        { size: 'M', color: 'Charcoal', stock: 20 },
        { size: 'L', color: 'Charcoal', stock: 25 },
        { size: 'XL', color: 'Charcoal', stock: 18 },
        { size: '2XL', color: 'Charcoal', stock: 10 },
      ],
    },
  ];

  for (const product of swagProducts) {
    const { variants, ...productData } = product;
    
    const createdProduct = await prisma.swagProduct.create({
      data: {
        ...productData,
        variants: {
          create: variants.map((v, idx) => ({
            sku: `${product.sku}-${v.size.replace(/\s/g, '')}-${v.color.replace(/[\s\/]/g, '')}`.toUpperCase(),
            size: v.size,
            color: v.color,
            stock: v.stock,
          })),
        },
      },
    });

    // Also create matching inventory products for GFS integration
    const existingProduct = await prisma.product.findFirst({
      where: { sku: product.sku },
    });

    if (!existingProduct) {
      await prisma.product.create({
        data: {
          sku: product.sku,
          name: product.name,
          description: product.description,
          category: `swag-${product.category}`,
          unit: 'each',
          costPrice: product.basePrice * 0.4, // 60% margin
          salePrice: product.basePrice,
          reorderLevel: 20,
          reorderQuantity: 50,
          isActive: true,
        },
      });
    }

    console.log(`  ✓ Created ${product.name} with ${variants.length} variants`);
  }

  console.log('✅ Swag Store products seeded!');

  // =============
  // SYSTEM TASKS
  // =============
  console.log('⚙️ Initializing System Tasks...');
  
  const SYSTEM_TASKS = [
    // Finance & AR
    { taskKey: 'dunning_runner', name: 'Daily Dunning Runner', description: 'Scan overdue AR records, escalate dunning levels, send automated payment reminders', category: 'finance', schedule: '0 9 * * *', isDefaultEnabled: true, isCritical: false },
    { taskKey: 'bank_reconciliation', name: 'Nightly Bank Reconciliation', description: 'Match Stripe payouts against AR records, flag discrepancies for human review', category: 'finance', schedule: '0 2 * * *', isDefaultEnabled: true, isCritical: false },
    { taskKey: 'cash_flow_forecast', name: 'Weekly Cash Flow Forecast', description: 'Aggregate AR aging + expected payouts, email executive summary', category: 'finance', schedule: '0 8 * * 1', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'ap_aging_alert', name: 'AP Aging Alert', description: 'Flag bills approaching due dates, prevent late payment fees', category: 'finance', schedule: '0 7 * * *', isDefaultEnabled: false, isCritical: false },
    
    // Security & Compliance
    { taskKey: 'heartbeat_monitor', name: 'Heartbeat Monitor', description: 'Continuous pulse check on critical services, alert on failure', category: 'security', schedule: '*/15 * * * *', isDefaultEnabled: true, isCritical: true },
    { taskKey: 'audit_log_digest', name: 'Audit Log Digest', description: 'Daily summary of all agent actions, flagged anomalies', category: 'security', schedule: '0 6 * * *', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'access_review_reminder', name: 'Access Review Reminder', description: 'Monthly prompt to review user permissions/RBAC', category: 'security', schedule: '0 9 1 * *', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'compliance_checkpoint', name: 'Compliance Checkpoint', description: 'Weekly scan for policy drift, expired certs, config changes', category: 'security', schedule: '0 10 * * 5', isDefaultEnabled: false, isCritical: false },
    
    // Marketing & Growth
    { taskKey: 'design_partner_digest', name: 'Design Partner Pipeline Digest', description: 'Daily email summarizing new applications, follow-up queue', category: 'marketing', schedule: '0 8 * * *', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'competitor_intel_scan', name: 'Competitor Intel Scan', description: 'Weekly scrape of competitor pricing/feature changes', category: 'marketing', schedule: '0 7 * * 1', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'content_calendar_reminder', name: 'Content Calendar Reminder', description: 'Weekly nudge with upcoming blog/social deadlines', category: 'marketing', schedule: '0 9 * * 1', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'lead_scoring_update', name: 'Lead Scoring Update', description: 'Nightly recalc of lead scores based on engagement signals', category: 'marketing', schedule: '0 3 * * *', isDefaultEnabled: false, isCritical: false },
    
    // Operations & Inventory
    { taskKey: 'inventory_reorder_trigger', name: 'Inventory Reorder Trigger', description: 'Check stock levels, auto-generate POs when below threshold', category: 'operations', schedule: '0 8 * * *', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'order_fulfillment_health', name: 'Order Fulfillment Health', description: 'Daily summary of stuck/delayed orders', category: 'operations', schedule: '0 7 * * *', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'vendor_performance_report', name: 'Vendor Performance Report', description: 'Weekly scorecard on supplier SLAs', category: 'operations', schedule: '0 9 * * 1', isDefaultEnabled: false, isCritical: false },
    
    // Data & Backup
    { taskKey: 'database_snapshot_verify', name: 'Database Snapshot Verify', description: 'Nightly logical backup verification', category: 'data', schedule: '0 4 * * *', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'data_retention_cleanup', name: 'Data Retention Cleanup', description: 'Monthly purge of soft-deleted records past retention window', category: 'data', schedule: '0 3 1 * *', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'schema_drift_check', name: 'Schema Drift Check', description: 'Alert if production schema diverges from expected state', category: 'data', schedule: '0 5 * * *', isDefaultEnabled: false, isCritical: false },
    
    // HR
    { taskKey: 'payroll_reminder', name: 'Payroll Processing Reminder', description: 'Reminder before payroll processing deadline', category: 'hr', schedule: '0 9 1,15 * *', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'leave_balance_alert', name: 'Leave Balance Alert', description: 'Monthly summary of PTO balances and expirations', category: 'hr', schedule: '0 9 1 * *', isDefaultEnabled: false, isCritical: false },
    
    // Executive Intelligence
    { taskKey: 'weekly_syndicate_brief', name: `Weekly ${VOCAB.brief}`, description: 'Auto-generated executive summary with metrics and insights', category: 'executive', schedule: '0 7 * * 1', isDefaultEnabled: false, isCritical: false },
    { taskKey: 'anomaly_digest', name: 'Anomaly Digest', description: 'Daily roll-up of pattern engine flags', category: 'executive', schedule: '0 8 * * *', isDefaultEnabled: false, isCritical: false },
  ];

  for (const task of SYSTEM_TASKS) {
    await prisma.systemTask.upsert({
      where: { taskKey: task.taskKey },
      update: {
        name: task.name,
        description: task.description,
        category: task.category,
        schedule: task.schedule,
        isCritical: task.isCritical,
      },
      create: {
        taskKey: task.taskKey,
        name: task.name,
        description: task.description,
        category: task.category,
        schedule: task.schedule,
        isEnabled: task.isDefaultEnabled,
        isDefaultEnabled: task.isDefaultEnabled,
        isCritical: task.isCritical,
      },
    });
  }

  const enabledTasks = SYSTEM_TASKS.filter(t => t.isDefaultEnabled);
  console.log(`✅ System Tasks initialized! ${enabledTasks.length} enabled by default (${enabledTasks.map(t => t.taskKey).join(', ')})`);

  // =============
  // REPORT DEFINITIONS
  // =============
  console.log('📊 Initializing Report Definitions...');
  
  const { initializeReportDefinitions } = await import('../lib/reports/report-definitions');
  const { initializeWidgetLibrary } = await import('../lib/reports/widget-library');
  
  await initializeReportDefinitions(prisma);
  await initializeWidgetLibrary(prisma);
  
  const reportCount = await prisma.reportDefinition.count();
  const widgetCount = await prisma.reportWidget.count();
  console.log(`✅ Report Definitions initialized! ${reportCount} reports, ${widgetCount} widgets`);

  // =============
  // ACCOUNTS RECEIVABLE (upsert - no deleteMany)
  // =============
  console.log('💰 Seeding Accounts Receivable...');
  const arRecords = [
    { id: 'ar-seed-001', orderId: 'SO-S0001', invoiceId: 'INV-AR-001', customerId: 'syn-cust-0001', customerEmail: 'billing@meridianhealthsystems.com', customerName: 'Meridian Health Systems', invoiceNumber: 'INV-AR-001', originalAmount: 12500.00, amountPaid: 12500.00, amountDue: 0, status: 'paid', dueDate: new Date('2026-02-15'), paidDate: new Date('2026-02-10'), daysPastDue: 0, dunningLevel: 0 },
    { id: 'ar-seed-002', orderId: 'SO-S0002', invoiceId: 'INV-AR-002', customerId: 'syn-cust-0002', customerEmail: 'billing@cascadefinancialgroup.com', customerName: 'Cascade Financial Group', invoiceNumber: 'INV-AR-002', originalAmount: 8750.00, amountPaid: 0, amountDue: 8750.00, status: 'overdue', dueDate: new Date('2026-02-01'), daysPastDue: 40, dunningLevel: 2, lastDunningDate: new Date('2026-03-05') },
    { id: 'ar-seed-003', orderId: 'SO-S0003', invoiceId: 'INV-AR-003', customerId: 'syn-cust-0003', customerEmail: 'billing@redwoodmanufacturing.com', customerName: 'Redwood Manufacturing', invoiceNumber: 'INV-AR-003', originalAmount: 22000.00, amountPaid: 11000.00, amountDue: 11000.00, status: 'partial', dueDate: new Date('2026-03-01'), daysPastDue: 12, dunningLevel: 1, lastDunningDate: new Date('2026-03-10') },
    { id: 'ar-seed-004', orderId: 'SO-S0004', invoiceId: 'INV-AR-004', customerId: 'syn-cust-0004', customerEmail: 'billing@bluewaveanalytics.com', customerName: 'BlueWave Analytics', invoiceNumber: 'INV-AR-004', originalAmount: 5200.00, amountPaid: 0, amountDue: 5200.00, status: 'open', dueDate: new Date('2026-03-25'), daysPastDue: 0, dunningLevel: 0 },
    { id: 'ar-seed-005', orderId: 'SO-S0005', invoiceId: 'INV-AR-005', customerId: 'syn-cust-0005', customerEmail: 'billing@sterlingautomotive.com', customerName: 'Sterling Automotive', invoiceNumber: 'INV-AR-005', originalAmount: 45000.00, amountPaid: 0, amountDue: 45000.00, status: 'overdue', dueDate: new Date('2026-01-15'), daysPastDue: 57, dunningLevel: 3, lastDunningDate: new Date('2026-03-08') },
    { id: 'ar-seed-006', orderId: 'SO-S0006', invoiceId: 'INV-AR-006', customerEmail: 'orders@techstart.io', customerName: 'TechStart Inc', invoiceNumber: 'INV-AR-006', originalAmount: 3400.00, amountPaid: 3400.00, amountDue: 0, status: 'paid', dueDate: new Date('2026-03-10'), paidDate: new Date('2026-03-08'), daysPastDue: 0, dunningLevel: 0 },
    { id: 'ar-seed-007', orderId: 'SO-S0007', invoiceId: 'INV-AR-007', customerEmail: 'procurement@acme.com', customerName: 'Acme Corporation', invoiceNumber: 'INV-AR-007', originalAmount: 18900.00, amountPaid: 0, amountDue: 18900.00, status: 'overdue', dueDate: new Date('2026-02-20'), daysPastDue: 21, dunningLevel: 1, lastDunningDate: new Date('2026-03-11') },
    { id: 'ar-seed-008', orderId: 'SO-S0008', invoiceId: 'INV-AR-008', customerEmail: 'buyer@globalretail.com', customerName: 'Global Retail Partners', invoiceNumber: 'INV-AR-008', originalAmount: 7600.00, amountPaid: 0, amountDue: 7600.00, status: 'open', dueDate: new Date('2026-04-01'), daysPastDue: 0, dunningLevel: 0 },
  ];
  for (const ar of arRecords) {
    await prisma.accountsReceivable.upsert({ where: { id: ar.id }, update: ar, create: ar });
  }
  console.log(`✅ Accounts Receivable seeded: ${arRecords.length} records`);

  // =============
  // BANK RECONCILIATION (upsert - no deleteMany)
  // =============
  console.log('🏦 Seeding Bank Reconciliation...');
  const bankRecords = [
    { id: 'br-seed-001', reconciliationId: 'RECON-2026-01', periodStart: new Date('2026-01-01'), periodEnd: new Date('2026-01-31'), expectedAmount: 87500.00, actualAmount: 87500.00, discrepancy: 0, status: 'reconciled', matchedArIds: JSON.stringify(['ar-seed-001']), unmatchedItems: JSON.stringify([]), notes: 'January reconciliation - all matched', resolvedBy: 'scott@spookysoftwaresyndicate.com', resolvedAt: new Date('2026-02-05') },
    { id: 'br-seed-002', reconciliationId: 'RECON-2026-02', periodStart: new Date('2026-02-01'), periodEnd: new Date('2026-02-28'), expectedAmount: 64200.00, actualAmount: 62850.00, discrepancy: 1350.00, status: 'discrepancy', matchedArIds: JSON.stringify(['ar-seed-006']), unmatchedItems: JSON.stringify([{ type: 'missing_payment', amount: 1350, reference: 'CHK-29481' }]), notes: 'February - $1,350 check not yet cleared' },
    { id: 'br-seed-003', reconciliationId: 'RECON-2026-03', periodStart: new Date('2026-03-01'), periodEnd: new Date('2026-03-13'), expectedAmount: 41600.00, actualAmount: 26500.00, discrepancy: 15100.00, status: 'pending', matchedArIds: JSON.stringify([]), unmatchedItems: JSON.stringify([{ type: 'pending_deposit', amount: 11000, reference: 'ar-seed-003' }, { type: 'pending_wire', amount: 4100, reference: 'WIRE-88421' }]) },
  ];
  for (const br of bankRecords) {
    await prisma.bankReconciliation.upsert({ where: { id: br.id }, update: br, create: br });
  }
  console.log(`✅ Bank Reconciliation seeded: ${bankRecords.length} records`);

  // =============
  // DUNNING HISTORY (upsert - no deleteMany)
  // =============
  console.log('📧 Seeding Dunning History...');
  const dunningRecords = [
    { id: 'dh-seed-001', arId: 'ar-seed-002', dunningLevel: 1, emailSent: true, emailRecipient: 'billing@cascadefinancialgroup.com', emailSubject: 'Payment Reminder - Invoice INV-AR-002', emailContent: 'This is a friendly reminder that your invoice INV-AR-002 for $8,750.00 is past due.', sentAt: new Date('2026-02-15') },
    { id: 'dh-seed-002', arId: 'ar-seed-002', dunningLevel: 2, emailSent: true, emailRecipient: 'billing@cascadefinancialgroup.com', emailSubject: 'Second Notice - Invoice INV-AR-002 Overdue', emailContent: 'Your invoice INV-AR-002 for $8,750.00 is now 30+ days past due. Please arrange payment immediately.', sentAt: new Date('2026-03-05') },
    { id: 'dh-seed-003', arId: 'ar-seed-003', dunningLevel: 1, emailSent: true, emailRecipient: 'billing@redwoodmanufacturing.com', emailSubject: 'Payment Reminder - Invoice INV-AR-003 Balance Due', emailContent: 'A balance of $11,000.00 remains on invoice INV-AR-003. Your partial payment of $11,000.00 has been received.', sentAt: new Date('2026-03-10') },
    { id: 'dh-seed-004', arId: 'ar-seed-005', dunningLevel: 1, emailSent: true, emailRecipient: 'billing@sterlingautomotive.com', emailSubject: 'Payment Reminder - Invoice INV-AR-005', sentAt: new Date('2026-02-01') },
    { id: 'dh-seed-005', arId: 'ar-seed-005', dunningLevel: 2, emailSent: true, emailRecipient: 'billing@sterlingautomotive.com', emailSubject: 'Second Notice - Invoice INV-AR-005', sentAt: new Date('2026-02-20') },
    { id: 'dh-seed-006', arId: 'ar-seed-005', dunningLevel: 3, emailSent: true, emailRecipient: 'billing@sterlingautomotive.com', emailSubject: 'URGENT: Final Notice - Invoice INV-AR-005 ($45,000)', emailContent: 'This is your final notice. Invoice INV-AR-005 for $45,000.00 is now 57 days past due. Failure to pay may result in account suspension.', sentAt: new Date('2026-03-08') },
    { id: 'dh-seed-007', arId: 'ar-seed-007', dunningLevel: 1, emailSent: true, emailRecipient: 'procurement@acme.com', emailSubject: 'Payment Reminder - Invoice INV-AR-007', emailContent: 'Friendly reminder: Invoice INV-AR-007 for $18,900.00 was due on Feb 20. Please process at your earliest convenience.', sentAt: new Date('2026-03-11') },
  ];
  for (const dh of dunningRecords) {
    await prisma.dunningHistory.upsert({ where: { id: dh.id }, update: dh, create: dh });
  }
  console.log(`✅ Dunning History seeded: ${dunningRecords.length} records`);

  // =============
  // SENTINEL RULES (upsert - no deleteMany)
  // =============
  console.log('🛡️ Seeding Sentinel Rules...');
  const sentinelRules = [
    { id: 'sr-seed-001', name: 'High Value Invoice Overdue', description: 'Triggers when an invoice over $10K is more than 30 days past due', type: 'threshold', category: 'finance', condition: { field: 'amountDue', operator: 'gt', value: 10000 }, threshold: { daysPastDue: 30 }, triggerOn: 'invoice_overdue', eventTypes: JSON.stringify(['invoice.overdue']), severity: 'high', autoRespond: true, responseActions: JSON.stringify([{ action: 'send_dunning', level: 2 }, { action: 'notify_admin' }]), enabled: true, triggerCount: 3 },
    { id: 'sr-seed-002', name: 'Unusual Transaction Volume', description: 'Detects when daily transaction count exceeds 3x the 30-day average', type: 'anomaly', category: 'security', condition: { metric: 'daily_transactions', multiplier: 3, baseline: '30d_avg' }, triggerOn: 'transaction_spike', eventTypes: JSON.stringify(['transaction.created']), severity: 'critical', autoRespond: false, enabled: true, triggerCount: 1 },
    { id: 'sr-seed-003', name: 'Inventory Below Safety Stock', description: 'Alerts when any SKU drops below minimum safety stock level', type: 'threshold', category: 'operations', condition: { field: 'quantity', operator: 'lt', compareField: 'safetyStock' }, triggerOn: 'inventory_low', eventTypes: JSON.stringify(['inventory.updated']), severity: 'medium', autoRespond: true, responseActions: JSON.stringify([{ action: 'create_purchase_order' }]), enabled: true, triggerCount: 8 },
    { id: 'sr-seed-004', name: 'Failed Login Attempts', description: 'Triggers after 5 failed login attempts within 15 minutes from same IP', type: 'pattern', category: 'security', condition: { event: 'login_failed', count: 5, window: '15m', groupBy: 'ip_address' }, pattern: 'brute_force', triggerOn: 'auth_failure', eventTypes: JSON.stringify(['auth.login_failed']), severity: 'critical', autoRespond: true, responseActions: JSON.stringify([{ action: 'block_ip', duration: '1h' }, { action: 'notify_admin' }]), enabled: true, triggerCount: 0 },
    { id: 'sr-seed-005', name: 'Revenue Target Miss', description: 'Alerts when monthly revenue tracking falls below 80% of target at month midpoint', type: 'threshold', category: 'finance', condition: { metric: 'monthly_revenue', operator: 'lt', percentOfTarget: 80 }, threshold: { checkAt: 'mid_month' }, triggerOn: 'revenue_tracking', eventTypes: JSON.stringify(['report.monthly']), severity: 'high', autoRespond: false, enabled: true, triggerCount: 1 },
    { id: 'sr-seed-006', name: 'Employee Overtime Alert', description: 'Detects employees logging more than 50 hours in a work week', type: 'threshold', category: 'hr', condition: { field: 'weekly_hours', operator: 'gt', value: 50 }, triggerOn: 'timeentry_exceeded', eventTypes: JSON.stringify(['timeentry.created']), severity: 'medium', autoRespond: false, enabled: true, triggerCount: 5 },
  ];
  for (const rule of sentinelRules) {
    await prisma.sentinelRule.upsert({ where: { id: rule.id }, update: rule, create: rule });
  }
  console.log(`✅ Sentinel Rules seeded: ${sentinelRules.length} rules`);

  // =============
  // SENTINEL ALERTS (upsert - no deleteMany)
  // =============
  console.log('🚨 Seeding Sentinel Alerts...');
  const sentinelAlerts = [
    { id: 'sa-seed-001', type: 'threshold', severity: 'high', category: 'finance', source: 'sentinel-rule-engine', triggerId: 'sr-seed-001', targetType: 'accountsReceivable', targetId: 'ar-seed-005', targetName: 'Sterling Automotive - INV-AR-005', title: 'High Value Invoice 57 Days Overdue', description: 'Invoice INV-AR-005 for $45,000 from Sterling Automotive is 57 days past due. Dunning level 3 reached.', evidence: JSON.stringify({ invoiceAmount: 45000, daysPastDue: 57, dunningLevel: 3 }), riskScore: 85, confidence: 0.95, status: 'escalated', detectedAt: new Date('2026-03-08') },
    { id: 'sa-seed-002', type: 'threshold', severity: 'medium', category: 'finance', source: 'sentinel-rule-engine', triggerId: 'sr-seed-001', targetType: 'accountsReceivable', targetId: 'ar-seed-002', targetName: 'Cascade Financial - INV-AR-002', title: 'Invoice $8,750 Past Due 40 Days', description: 'Invoice INV-AR-002 from Cascade Financial Group has been overdue for 40 days.', evidence: JSON.stringify({ invoiceAmount: 8750, daysPastDue: 40, dunningLevel: 2 }), riskScore: 60, confidence: 0.9, status: 'open', detectedAt: new Date('2026-03-05') },
    { id: 'sa-seed-003', type: 'anomaly', severity: 'critical', category: 'security', source: 'sentinel-rule-engine', triggerId: 'sr-seed-002', title: 'Unusual Transaction Spike Detected', description: 'Transaction volume on March 7 was 3.2x the 30-day average. 47 transactions detected vs 15 avg.', evidence: JSON.stringify({ dailyCount: 47, avgCount: 15, multiplier: 3.2, date: '2026-03-07' }), riskScore: 78, confidence: 0.88, status: 'acknowledged', acknowledgedAt: new Date('2026-03-07'), detectedAt: new Date('2026-03-07') },
    { id: 'sa-seed-004', type: 'threshold', severity: 'medium', category: 'operations', source: 'sentinel-rule-engine', triggerId: 'sr-seed-003', targetType: 'inventoryItem', targetName: 'Widget Pro X100', title: 'Inventory Below Safety Stock', description: 'Widget Pro X100 has dropped to 12 units, below the safety stock of 25.', evidence: JSON.stringify({ currentStock: 12, safetyStock: 25, reorderPoint: 50 }), riskScore: 45, confidence: 0.99, status: 'resolved', resolvedAt: new Date('2026-03-10'), resolvedBy: 'scott@spookysoftwaresyndicate.com', resolution: 'Purchase order PO-2026-042 placed for 100 units', detectedAt: new Date('2026-03-09') },
    { id: 'sa-seed-005', type: 'threshold', severity: 'high', category: 'finance', source: 'sentinel-rule-engine', triggerId: 'sr-seed-005', title: 'March Revenue Tracking Below Target', description: 'As of March 13, monthly revenue is at 62% of the $200K target. At risk of missing goal.', evidence: JSON.stringify({ currentRevenue: 124000, targetRevenue: 200000, percentAchieved: 62, daysRemaining: 18 }), riskScore: 72, confidence: 0.85, status: 'open', detectedAt: new Date('2026-03-13') },
    { id: 'sa-seed-006', type: 'threshold', severity: 'medium', category: 'hr', source: 'sentinel-rule-engine', triggerId: 'sr-seed-006', targetType: 'employee', targetName: 'Marcus Chen', title: 'Employee Overtime: 54 Hours This Week', description: 'Marcus Chen has logged 54 hours this week, exceeding the 50-hour overtime threshold.', evidence: JSON.stringify({ employeeName: 'Marcus Chen', hoursLogged: 54, threshold: 50, weekOf: '2026-03-09' }), riskScore: 40, confidence: 0.99, status: 'open', detectedAt: new Date('2026-03-12') },
  ];
  for (const alert of sentinelAlerts) {
    await prisma.sentinelAlert.upsert({ where: { id: alert.id }, update: alert, create: alert });
  }
  console.log(`✅ Sentinel Alerts seeded: ${sentinelAlerts.length} alerts`);

  // =============
  // SWAG ORDERS (upsert - no deleteMany)
  // =============
  console.log('🛍️ Seeding Swag Orders...');
  const swagOrders = [
    {
      id: 'so-seed-001', orderNumber: 'SWAG-0001', customerName: 'Scott Murphy', customerEmail: 'scott@spookysoftwaresyndicate.com',
      shippingAddress: JSON.stringify({ street: '123 Ghost Lane', city: 'Austin', state: 'TX', zip: '78701', country: 'US' }),
      status: 'delivered', subtotal: 189.97, tax: 15.65, shipping: 0, total: 205.62, paymentStatus: 'paid', paymentMethod: 'stripe',
      trackingNumber: 'USP-1Z999AA10123456784', createdAt: new Date('2026-02-20'), metadata: JSON.stringify({ source: 'website' })
    },
    {
      id: 'so-seed-002', orderNumber: 'SWAG-0002', customerName: 'Jamie Torres', customerEmail: 'jamie@meridianhealth.com',
      shippingAddress: JSON.stringify({ street: '456 Oak Avenue', city: 'Denver', state: 'CO', zip: '80202', country: 'US' }),
      status: 'shipped', subtotal: 79.99, tax: 6.40, shipping: 5.99, total: 92.38, paymentStatus: 'paid', paymentMethod: 'stripe',
      trackingNumber: 'FDX-794644790138', createdAt: new Date('2026-03-05'), metadata: JSON.stringify({ source: 'design_partner' })
    },
    {
      id: 'so-seed-003', orderNumber: 'SWAG-0003', customerName: 'Alex Kim', customerEmail: 'alex@bluewaveanalytics.com',
      shippingAddress: JSON.stringify({ street: '789 Market St', city: 'San Francisco', state: 'CA', zip: '94105', country: 'US' }),
      status: 'processing', subtotal: 249.95, tax: 22.50, shipping: 0, total: 272.45, paymentStatus: 'paid', paymentMethod: 'stripe',
      createdAt: new Date('2026-03-11'), metadata: JSON.stringify({ source: 'website', notes: 'Bulk order for team' })
    },
    {
      id: 'so-seed-004', orderNumber: 'SWAG-0004', customerName: 'Morgan Blake', customerEmail: 'morgan@cascadefinancial.com',
      shippingAddress: JSON.stringify({ street: '321 Pine Rd', city: 'Seattle', state: 'WA', zip: '98101', country: 'US' }),
      status: 'pending', subtotal: 64.99, tax: 6.50, shipping: 5.99, total: 77.48, paymentStatus: 'pending',
      createdAt: new Date('2026-03-13'), metadata: JSON.stringify({ source: 'website' })
    },
  ];
  for (const order of swagOrders) {
    await prisma.swagOrder.upsert({ where: { id: order.id }, update: order, create: order });
  }

  // Swag Order Items - dynamically look up product/variant IDs by name
  const currentSwagProducts = await prisma.swagProduct.findMany({ select: { id: true, name: true } });
  const getProductId = (name: string) => currentSwagProducts.find((p: any) => p.name.includes(name))?.id;
  const hoodieId = getProductId('Classic Hoodie');
  const operatorId = getProductId('Operator Hoodie');
  const techTeeId = getProductId('Tech Tee');
  const remembersId = getProductId('Remembers Tee');
  const snapbackId = getProductId('Snapback');

  if (hoodieId && operatorId && techTeeId) {
    const getVariantId = async (productId: string) => {
      const v = await prisma.swagVariant.findFirst({ where: { productId }, select: { id: true } });
      return v?.id;
    };
    const hoodieVar = await getVariantId(hoodieId);
    const operatorVar = await getVariantId(operatorId);
    const techTeeVar = await getVariantId(techTeeId);
    const remembersVar = remembersId ? await getVariantId(remembersId) : techTeeVar;
    const snapbackVar = snapbackId ? await getVariantId(snapbackId) : techTeeVar;

    if (hoodieVar && operatorVar && techTeeVar) {
      const orderItems = [
        { id: 'soi-seed-001', orderId: 'so-seed-001', productId: hoodieId, variantId: hoodieVar, quantity: 1, unitPrice: 79.99, totalPrice: 79.99 },
        { id: 'soi-seed-002', orderId: 'so-seed-001', productId: operatorId, variantId: operatorVar, quantity: 1, unitPrice: 74.99, totalPrice: 74.99 },
        { id: 'soi-seed-003', orderId: 'so-seed-001', productId: techTeeId, variantId: techTeeVar, quantity: 1, unitPrice: 34.99, totalPrice: 34.99 },
        { id: 'soi-seed-004', orderId: 'so-seed-002', productId: techTeeId, variantId: techTeeVar, quantity: 1, unitPrice: 34.99, totalPrice: 34.99 },
        { id: 'soi-seed-005', orderId: 'so-seed-002', productId: remembersId || techTeeId, variantId: remembersVar || techTeeVar, quantity: 1, unitPrice: 44.99, totalPrice: 44.99 },
        { id: 'soi-seed-006', orderId: 'so-seed-003', productId: hoodieId, variantId: hoodieVar, quantity: 3, unitPrice: 79.99, totalPrice: 239.97 },
        { id: 'soi-seed-007', orderId: 'so-seed-004', productId: snapbackId || techTeeId, variantId: snapbackVar || techTeeVar, quantity: 2, unitPrice: 32.50, totalPrice: 64.99 },
      ];
      for (const item of orderItems) {
        await prisma.swagOrderItem.upsert({ where: { id: item.id }, update: item, create: item });
      }
      console.log(`✅ Swag Orders seeded: ${swagOrders.length} orders, ${orderItems.length} items`);
    } else {
      console.log(`✅ Swag Orders seeded: ${swagOrders.length} orders (skipped items - variants not found)`);
    }
  } else {
    console.log(`✅ Swag Orders seeded: ${swagOrders.length} orders (skipped items - products not found)`);
  }

  // =============
  // AGENTS (required by workflow steps)
  // =============
  console.log('⚙️ Seeding Agents...');
  const agents = [
    { id: 'syn-agent-0001', name: 'Finance Agent', type: 'finance', status: 'active', description: 'Handles financial operations, invoicing, and AR/AP' },
    { id: 'syn-agent-0002', name: 'HR Agent', type: 'hr', status: 'active', description: 'Handles human resources, onboarding, and employee management' },
  ];
  for (const agent of agents) {
    await prisma.agent.upsert({ where: { id: agent.id }, update: agent, create: { ...agent, capabilities: [], metrics: {} } });
  }
  console.log(`✅ Agents seeded: ${agents.length}`);

  // =============
  // WORKFLOWS (required by workflow steps)
  // =============
  console.log('⚙️ Seeding Workflows...');
  const workflows = [
    { id: 'syn-wf-0001', name: 'Invoice-to-Cash', description: 'Full AR cycle from invoice generation to payment reconciliation', createdById: 'syn-agent-0001', status: 'active', steps: [], trigger: { type: 'manual' } },
    { id: 'syn-wf-0002', name: 'Employee Onboarding', description: 'New hire setup from record creation to orientation', createdById: 'syn-agent-0002', status: 'active', steps: [], trigger: { type: 'manual' } },
    { id: 'syn-wf-0003', name: 'Month-End Close', description: 'Financial period close process', createdById: 'syn-agent-0001', status: 'active', steps: [], trigger: { type: 'scheduled', cron: '0 0 1 * *' } },
    { id: 'syn-wf-0004', name: 'Security Audit', description: 'Periodic security audit and compliance check', createdById: 'syn-agent-0001', status: 'active', steps: [], trigger: { type: 'scheduled', cron: '0 0 1 */3 *' } },
  ];
  for (const wf of workflows) {
    await prisma.workflow.upsert({ where: { id: wf.id }, update: { name: wf.name, description: wf.description }, create: wf });
  }
  console.log(`✅ Workflows seeded: ${workflows.length}`);

  // =============
  // WORKFLOW STEPS (upsert - no deleteMany)
  // =============
  console.log('⚙️ Seeding Workflow Steps...');
  const workflowSteps = [
    // Invoice-to-Cash workflow steps
    { id: 'ws-seed-001', workflowId: 'syn-wf-0001', name: 'Generate Invoice', description: 'Create and send invoice to customer', order: 1, action: JSON.stringify({ type: 'create_invoice', template: 'standard' }), agentId: 'syn-agent-0001' },
    { id: 'ws-seed-002', workflowId: 'syn-wf-0001', name: 'Track Payment', description: 'Monitor payment status and due dates', order: 2, action: JSON.stringify({ type: 'monitor_payment', checkInterval: '24h' }), agentId: 'syn-agent-0001', conditions: JSON.stringify({ waitFor: 'invoice_sent' }) },
    { id: 'ws-seed-003', workflowId: 'syn-wf-0001', name: 'Dunning Escalation', description: 'Send payment reminders at escalating urgency', order: 3, action: JSON.stringify({ type: 'send_dunning', levels: [1, 2, 3] }), agentId: 'syn-agent-0001', conditions: JSON.stringify({ trigger: 'payment_overdue' }), timeout: 86400 },
    { id: 'ws-seed-004', workflowId: 'syn-wf-0001', name: 'Reconcile Payment', description: 'Match incoming payment to invoice and close AR record', order: 4, action: JSON.stringify({ type: 'reconcile', autoMatch: true }), agentId: 'syn-agent-0001' },
    // Employee Onboarding workflow steps
    { id: 'ws-seed-005', workflowId: 'syn-wf-0002', name: 'Create Employee Record', description: 'Set up employee in HR system with department assignment', order: 1, action: JSON.stringify({ type: 'create_employee', requireFields: ['name', 'email', 'department', 'role'] }), agentId: 'syn-agent-0002' },
    { id: 'ws-seed-006', workflowId: 'syn-wf-0002', name: 'Provision Access', description: 'Grant system access and create user accounts', order: 2, action: JSON.stringify({ type: 'provision_access', systems: ['email', 'slack', 'erp'] }), agentId: 'syn-agent-0002' },
    { id: 'ws-seed-007', workflowId: 'syn-wf-0002', name: 'Assign Equipment', description: 'Allocate laptop, badge, and workspace', order: 3, action: JSON.stringify({ type: 'assign_equipment', items: ['laptop', 'badge', 'workspace'] }) },
    { id: 'ws-seed-008', workflowId: 'syn-wf-0002', name: 'Schedule Orientation', description: 'Book orientation sessions and mentor assignment', order: 4, action: JSON.stringify({ type: 'schedule_orientation', duration: '3_days' }), agentId: 'syn-agent-0002' },
    // Monthly Close workflow steps
    { id: 'ws-seed-009', workflowId: 'syn-wf-0003', name: 'Close Sub-Ledgers', description: 'Close all sub-ledger accounts for the period', order: 1, action: JSON.stringify({ type: 'close_subledgers', ledgers: ['AP', 'AR', 'inventory'] }), agentId: 'syn-agent-0001' },
    { id: 'ws-seed-010', workflowId: 'syn-wf-0003', name: 'Run Reconciliation', description: 'Reconcile bank statements against internal records', order: 2, action: JSON.stringify({ type: 'bank_reconciliation' }), agentId: 'syn-agent-0001' },
    { id: 'ws-seed-011', workflowId: 'syn-wf-0003', name: 'Generate Financial Reports', description: 'Produce P&L, balance sheet, and cash flow statements', order: 3, action: JSON.stringify({ type: 'generate_reports', reports: ['pnl', 'balance_sheet', 'cashflow'] }), agentId: 'syn-agent-0001' },
    // Security Audit workflow steps
    { id: 'ws-seed-012', workflowId: 'syn-wf-0004', name: 'Scan Access Logs', description: 'Review all system access logs for anomalies', order: 1, action: JSON.stringify({ type: 'scan_logs', period: '30d' }) },
    { id: 'ws-seed-013', workflowId: 'syn-wf-0004', name: 'Verify Permissions', description: 'Audit user permissions against role requirements', order: 2, action: JSON.stringify({ type: 'audit_permissions' }) },
    { id: 'ws-seed-014', workflowId: 'syn-wf-0004', name: 'Generate Audit Report', description: 'Compile findings into security audit report', order: 3, action: JSON.stringify({ type: 'generate_audit_report' }) },
  ];
  for (const step of workflowSteps) {
    await prisma.workflowStep.upsert({ where: { id: step.id }, update: step, create: step });
  }
  console.log(`✅ Workflow Steps seeded: ${workflowSteps.length} steps`);

  // =============
  // DARK FACTORY JOBS (upsert - no deleteMany)
  // =============
  console.log('🏭 Seeding The Hearth Jobs...');
  const darkFactoryJobs = [
    { id: 'dfj-seed-001', jobType: 'code_generation', triggerSource: 'manual', status: 'completed', input: JSON.stringify({ project: 'E-Commerce Backend', task: 'Generate REST API endpoints for product catalog' }), output: JSON.stringify({ filesGenerated: 8, linesOfCode: 1240, testsPassed: 24 }), artifactIds: JSON.stringify(['artifact-001', 'artifact-002']), startedAt: new Date('2026-03-01T10:00:00Z'), completedAt: new Date('2026-03-01T10:03:22Z'), executionTimeMs: 202000 },
    { id: 'dfj-seed-002', jobType: 'test_generation', triggerSource: 'automated', status: 'completed', input: JSON.stringify({ project: 'POS', task: 'Generate integration tests for payment flow' }), output: JSON.stringify({ testsGenerated: 15, coverage: '87%' }), artifactIds: JSON.stringify(['artifact-003']), startedAt: new Date('2026-03-03T14:30:00Z'), completedAt: new Date('2026-03-03T14:31:45Z'), executionTimeMs: 105000 },
    { id: 'dfj-seed-003', jobType: 'documentation', triggerSource: 'manual', status: 'completed', input: JSON.stringify({ project: 'TimeClock', task: 'Generate API documentation' }), output: JSON.stringify({ docsGenerated: 3, format: 'markdown' }), artifactIds: JSON.stringify([]), startedAt: new Date('2026-03-05T09:15:00Z'), completedAt: new Date('2026-03-05T09:16:10Z'), executionTimeMs: 70000 },
    { id: 'dfj-seed-004', jobType: 'code_review', triggerSource: 'webhook', triggerId: 'gh-pr-142', status: 'completed', input: JSON.stringify({ repository: 'ghostfoundry-api', pullRequest: 142, files: 12 }), output: JSON.stringify({ issues: 3, suggestions: 7, severity: { critical: 0, warning: 3, info: 7 } }), startedAt: new Date('2026-03-08T16:00:00Z'), completedAt: new Date('2026-03-08T16:02:30Z'), executionTimeMs: 150000 },
    { id: 'dfj-seed-005', jobType: 'deployment', triggerSource: 'automated', status: 'completed', input: JSON.stringify({ project: 'K-12 POS System', environment: 'staging', version: '2.1.0' }), output: JSON.stringify({ deployed: true, url: 'https://staging-k12pos.example.com', healthCheck: 'passed' }), startedAt: new Date('2026-03-10T08:00:00Z'), completedAt: new Date('2026-03-10T08:05:12Z'), executionTimeMs: 312000 },
    { id: 'dfj-seed-006', jobType: 'code_generation', triggerSource: 'manual', status: 'running', input: JSON.stringify({ project: 'E-Commerce Backend', task: 'Implement real-time inventory sync with webhooks' }), startedAt: new Date('2026-03-13T09:30:00Z'), executionTimeMs: null },
    { id: 'dfj-seed-007', jobType: 'security_scan', triggerSource: 'scheduled', status: 'queued', input: JSON.stringify({ scope: 'all_projects', scanType: 'dependency_audit' }) },
    { id: 'dfj-seed-008', jobType: 'test_generation', triggerSource: 'manual', status: 'failed', input: JSON.stringify({ project: 'POS', task: 'Generate load tests for checkout flow' }), error: 'Timeout: test generation exceeded 5-minute limit. Partial results saved.', startedAt: new Date('2026-03-12T11:00:00Z'), completedAt: new Date('2026-03-12T11:05:00Z'), executionTimeMs: 300000 },
  ];
  for (const job of darkFactoryJobs) {
    await prisma.darkFactoryJob.upsert({ where: { id: job.id }, update: job, create: job });
  }
  console.log(`✅ The Hearth Jobs seeded: ${darkFactoryJobs.length} jobs`);

  // =============
  // POS CATEGORIES & MENU ITEMS
  // =============
  console.log('🍽️ Seeding POS Categories & Menu Items...');

  const posCategories = [
    { id: 'poscat-appetizers', name: 'appetizers', displayName: 'Appetizers', color: '#f59e0b', icon: 'Soup', sortOrder: 1 },
    { id: 'poscat-entrees', name: 'entrees', displayName: 'Entrées', color: '#ef4444', icon: 'Beef', sortOrder: 2 },
    { id: 'poscat-sides', name: 'sides', displayName: 'Sides', color: '#22c55e', icon: 'Salad', sortOrder: 3 },
    { id: 'poscat-drinks', name: 'drinks', displayName: 'Drinks', color: '#3b82f6', icon: 'Coffee', sortOrder: 4 },
    { id: 'poscat-desserts', name: 'desserts', displayName: 'Desserts', color: '#a855f7', icon: 'Cake', sortOrder: 5 },
    { id: 'poscat-beer-wine', name: 'beer_wine', displayName: 'Beer & Wine', color: '#d97706', icon: 'Wine', sortOrder: 6 },
  ];
  for (const cat of posCategories) {
    await prisma.pOSCategory.upsert({ where: { id: cat.id }, update: cat, create: cat });
  }
  console.log(`✅ POS Categories seeded: ${posCategories.length}`);

  const posMenuItems = [
    // Appetizers
    { id: 'posmi-wings', name: 'Buffalo Wings', shortName: 'Wings', categoryId: 'poscat-appetizers', price: 12.99, costPrice: 4.50, taxRate: 0.0825, color: '#f59e0b', sortOrder: 1, modifierGroups: JSON.stringify([{ name: 'Sauce', options: ['Mild', 'Medium', 'Hot', 'BBQ'], required: false }]) },
    { id: 'posmi-nachos', name: 'Loaded Nachos', shortName: 'Nachos', categoryId: 'poscat-appetizers', price: 10.99, costPrice: 3.80, taxRate: 0.0825, color: '#fbbf24', sortOrder: 2, modifierGroups: JSON.stringify([{ name: 'Add-Ons', options: ['Extra Cheese', 'Jalapeños', 'Sour Cream', 'Guac +$2'], required: false }]) },
    { id: 'posmi-mozz', name: 'Mozzarella Sticks', shortName: 'Mozz Stix', categoryId: 'poscat-appetizers', price: 8.99, costPrice: 2.40, taxRate: 0.0825, color: '#f97316', sortOrder: 3, modifierGroups: JSON.stringify([]) },
    // Entrees
    { id: 'posmi-burger', name: 'Classic Burger', shortName: 'Burger', categoryId: 'poscat-entrees', price: 14.99, costPrice: 5.20, taxRate: 0.0825, color: '#ef4444', sortOrder: 1, modifierGroups: JSON.stringify([{ name: 'Temp', options: ['Rare', 'Med-Rare', 'Medium', 'Med-Well', 'Well'], required: true }, { name: 'Extras', options: ['Bacon +$2', 'Avocado +$1.50', 'Extra Patty +$4'], required: false }]) },
    { id: 'posmi-steak', name: '12oz Ribeye', shortName: 'Ribeye', categoryId: 'poscat-entrees', price: 28.99, costPrice: 14.00, taxRate: 0.0825, color: '#dc2626', sortOrder: 2, modifierGroups: JSON.stringify([{ name: 'Temp', options: ['Rare', 'Med-Rare', 'Medium', 'Med-Well', 'Well'], required: true }]) },
    { id: 'posmi-salmon', name: 'Grilled Salmon', shortName: 'Salmon', categoryId: 'poscat-entrees', price: 22.99, costPrice: 10.50, taxRate: 0.0825, color: '#fb923c', sortOrder: 3, modifierGroups: JSON.stringify([{ name: 'Prep', options: ['Lemon Butter', 'Cajun', 'Teriyaki'], required: false }]) },
    { id: 'posmi-chicken', name: 'Grilled Chicken Breast', shortName: 'Chicken', categoryId: 'poscat-entrees', price: 16.99, costPrice: 5.80, taxRate: 0.0825, color: '#f87171', sortOrder: 4, modifierGroups: JSON.stringify([]) },
    { id: 'posmi-pasta', name: 'Fettuccine Alfredo', shortName: 'Alfredo', categoryId: 'poscat-entrees', price: 15.99, costPrice: 4.20, taxRate: 0.0825, color: '#fca5a5', sortOrder: 5, modifierGroups: JSON.stringify([{ name: 'Protein', options: ['Chicken +$4', 'Shrimp +$6', 'None'], required: false }]) },
    // Sides
    { id: 'posmi-fries', name: 'French Fries', shortName: 'Fries', categoryId: 'poscat-sides', price: 4.99, costPrice: 1.20, taxRate: 0.0825, color: '#22c55e', sortOrder: 1, modifierGroups: JSON.stringify([]) },
    { id: 'posmi-salad', name: 'House Salad', shortName: 'Salad', categoryId: 'poscat-sides', price: 6.99, costPrice: 2.00, taxRate: 0.0825, color: '#4ade80', sortOrder: 2, modifierGroups: JSON.stringify([{ name: 'Dressing', options: ['Ranch', 'Caesar', 'Vinaigrette', 'Blue Cheese'], required: false }]) },
    { id: 'posmi-rings', name: 'Onion Rings', shortName: 'O-Rings', categoryId: 'poscat-sides', price: 5.99, costPrice: 1.60, taxRate: 0.0825, color: '#86efac', sortOrder: 3, modifierGroups: JSON.stringify([]) },
    // Drinks
    { id: 'posmi-soda', name: 'Fountain Soda', shortName: 'Soda', categoryId: 'poscat-drinks', price: 2.99, costPrice: 0.40, taxRate: 0.0825, color: '#3b82f6', sortOrder: 1, modifierGroups: JSON.stringify([{ name: 'Type', options: ['Coke', 'Diet Coke', 'Sprite', 'Dr Pepper', 'Lemonade'], required: true }]) },
    { id: 'posmi-tea', name: 'Iced Tea', shortName: 'Tea', categoryId: 'poscat-drinks', price: 2.49, costPrice: 0.30, taxRate: 0.0825, color: '#60a5fa', sortOrder: 2, modifierGroups: JSON.stringify([{ name: 'Sweet', options: ['Sweet', 'Unsweet'], required: true }]) },
    { id: 'posmi-coffee', name: 'Fresh Brewed Coffee', shortName: 'Coffee', categoryId: 'poscat-drinks', price: 3.49, costPrice: 0.50, taxRate: 0.0825, color: '#93c5fd', sortOrder: 3, modifierGroups: JSON.stringify([]) },
    { id: 'posmi-water', name: 'Bottled Water', shortName: 'Water', categoryId: 'poscat-drinks', price: 1.99, costPrice: 0.25, taxRate: 0, color: '#bfdbfe', sortOrder: 4, modifierGroups: JSON.stringify([]) },
    // Desserts
    { id: 'posmi-cheesecake', name: 'NY Cheesecake', shortName: 'Cheesecake', categoryId: 'poscat-desserts', price: 8.99, costPrice: 2.80, taxRate: 0.0825, color: '#a855f7', sortOrder: 1, modifierGroups: JSON.stringify([{ name: 'Topping', options: ['Strawberry', 'Chocolate', 'Caramel', 'Plain'], required: false }]) },
    { id: 'posmi-brownie', name: 'Chocolate Brownie', shortName: 'Brownie', categoryId: 'poscat-desserts', price: 7.49, costPrice: 2.00, taxRate: 0.0825, color: '#c084fc', sortOrder: 2, modifierGroups: JSON.stringify([{ name: 'À la mode', options: ['With Ice Cream +$2', 'Without'], required: false }]) },
    // Beer & Wine
    { id: 'posmi-draft', name: 'Draft Beer', shortName: 'Draft', categoryId: 'poscat-beer-wine', price: 6.99, costPrice: 2.20, taxRate: 0.0825, color: '#d97706', sortOrder: 1, modifierGroups: JSON.stringify([{ name: 'Size', options: ['Pint', 'Half Pint'], required: true }]) },
    { id: 'posmi-housewine', name: 'House Wine', shortName: 'Wine', categoryId: 'poscat-beer-wine', price: 8.99, costPrice: 3.00, taxRate: 0.0825, color: '#b45309', sortOrder: 2, modifierGroups: JSON.stringify([{ name: 'Type', options: ['Red', 'White', 'Rosé'], required: true }]) },
  ];
  for (const item of posMenuItems) {
    await prisma.pOSMenuItem.upsert({ where: { id: item.id }, update: item, create: item });
  }
  console.log(`✅ POS Menu Items seeded: ${posMenuItems.length}`);

  // POS Stations
  const posStations = [
    { id: 'possta-register1', name: 'Register 1', stationType: 'register', location: 'Front Counter', layoutConfig: JSON.stringify({ columns: 4, showImages: false }), printerConfig: JSON.stringify({ receipt: 'USB-001', kitchen: 'NET-KITCHEN-01' }) },
    { id: 'possta-register2', name: 'Register 2', stationType: 'register', location: 'Bar', layoutConfig: JSON.stringify({ columns: 3, showImages: false }), printerConfig: JSON.stringify({ receipt: 'USB-002', bar: 'NET-BAR-01' }) },
    { id: 'possta-kds1', name: 'Kitchen Display', stationType: 'kitchen_display', location: 'Kitchen', layoutConfig: JSON.stringify({ view: 'ticket', maxTickets: 8 }), printerConfig: JSON.stringify({ kitchen: 'NET-KITCHEN-01' }) },
  ];
  for (const station of posStations) {
    await prisma.pOSStation.upsert({ where: { id: station.id }, update: station, create: station });
  }
  console.log(`✅ POS Stations seeded: ${posStations.length}`);

  console.log('✅ Seeding complete!');
}

main()
  .catch((e) => {
    console.error('❌ Seeding failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
