/**
 * Seed NextCRM — données de démonstration
 * Devise : XOF (Franc CFA UEMOA)
 * Run : npm run db:seed
 */
import {
  PrismaClient,
  UserRole,
  SubscriptionPlan,
  AccountType,
  InvoiceStatus,
  ExpenseStatus,
  QuoteStatus,
  RecurringFrequency,
  RecurringStatus,
} from "@prisma/client";
import bcrypt from "bcryptjs";

const prisma = new PrismaClient();

function r2(n: number) { return Math.round(n * 100) / 100; }

type ItemInput = {
  description: string;
  quantity: number;
  unitPrice: number;
  taxRate: number;
  discount?: number;
};

function calc(items: ItemInput[]) {
  let subtotal = 0, taxAmount = 0, discountAmount = 0;
  const rows = items.map((item, idx) => {
    const disc = item.discount ?? 0;
    const base = r2(item.quantity * item.unitPrice * (1 - disc / 100));
    const tax = r2(base * (item.taxRate / 100));
    subtotal += base;
    taxAmount += tax;
    discountAmount += r2(item.quantity * item.unitPrice * (disc / 100));
    return {
      description: item.description,
      quantity: item.quantity,
      unitPrice: item.unitPrice,
      taxRate: item.taxRate,
      taxAmount: tax,
      discount: disc,
      total: r2(base + tax),
      order: idx,
    };
  });
  return {
    rows,
    subtotal: r2(subtotal),
    taxAmount: r2(taxAmount),
    discountAmount: r2(discountAmount),
    total: r2(subtotal + taxAmount),
  };
}

async function main() {
  console.log("🌱 Démarrage du seed…\n");

  // ══════════════════════════════════════════════════
  // UTILISATEURS
  // ══════════════════════════════════════════════════

  const adminPwd = await bcrypt.hash("Admin@123!", 12);
  const admin = await prisma.user.upsert({
    where: { email: "admin@nextcrm.io" },
    update: {},
    create: { email: "admin@nextcrm.io", name: "Super Admin", password: adminPwd, isSuperAdmin: true, emailVerified: new Date() },
  });
  console.log("✅ Admin:", admin.email);

  const demoPwd = await bcrypt.hash("Demo@123!", 12);
  const demoUser = await prisma.user.upsert({
    where: { email: "demo@nextcrm.io" },
    update: {},
    create: { email: "demo@nextcrm.io", name: "Amadou Diallo", password: demoPwd, emailVerified: new Date() },
  });
  console.log("✅ Utilisateur démo:", demoUser.email);

  // ══════════════════════════════════════════════════
  // ORGANISATION
  // ══════════════════════════════════════════════════

  const org = await prisma.organization.upsert({
    where: { slug: "diallo-consulting" },
    update: {},
    create: {
      name: "Diallo Consulting SARL",
      slug: "diallo-consulting",
      email: "contact@diallo-consulting.sn",
      phone: "+221 33 123 45 67",
      address: "Plateau, Avenue Léopold Sédar Senghor",
      city: "Dakar",
      postalCode: "BP 1234",
      country: "SN",
      vatNumber: "SN-TVA-2024-001",
      siret: "SN12345678",
      currency: "XOF",
      fiscalYearStart: 1,
      invoicePrefix: "FAC",
      invoiceCounter: 8,
    },
  });
  console.log("✅ Organisation:", org.name);

  await prisma.organizationMember.upsert({
    where: { organizationId_userId: { organizationId: org.id, userId: demoUser.id } },
    update: {},
    create: { organizationId: org.id, userId: demoUser.id, role: UserRole.OWNER, joinedAt: new Date() },
  });

  await prisma.subscription.upsert({
    where: { organizationId: org.id },
    update: {},
    create: { organizationId: org.id, plan: SubscriptionPlan.FREE, status: "ACTIVE" },
  });

  // ══════════════════════════════════════════════════
  // TAUX DE TVA (UEMOA)
  // ══════════════════════════════════════════════════

  for (const tr of [
    { name: "TVA 18% (Sénégal)", rate: 18, isDefault: true },
    { name: "TVA 10% (réduit)", rate: 10 },
    { name: "Exonéré (0%)", rate: 0 },
  ]) {
    await prisma.taxRate.upsert({
      where: { organizationId_name: { organizationId: org.id, name: tr.name } } as any,
      update: {},
      create: { organizationId: org.id, name: tr.name, rate: tr.rate, isDefault: tr.isDefault ?? false, country: "SN" },
    });
  }
  console.log("✅ Taux de TVA créés");

  // ══════════════════════════════════════════════════
  // PLAN COMPTABLE (SYSCOHADA)
  // ══════════════════════════════════════════════════

  const pcg = [
    { code: "101000", name: "Capital social", type: AccountType.EQUITY },
    { code: "111000", name: "Réserves légales", type: AccountType.EQUITY },
    { code: "130000", name: "Résultat net de l'exercice", type: AccountType.EQUITY },
    { code: "161000", name: "Emprunts", type: AccountType.LIABILITY },
    { code: "401000", name: "Fournisseurs", type: AccountType.LIABILITY },
    { code: "411000", name: "Clients", type: AccountType.ASSET },
    { code: "421000", name: "Personnel — Rémunérations dues", type: AccountType.LIABILITY },
    { code: "441000", name: "État — Impôts et taxes", type: AccountType.LIABILITY },
    { code: "443000", name: "TVA collectée", type: AccountType.LIABILITY },
    { code: "445000", name: "TVA déductible", type: AccountType.ASSET },
    { code: "521000", name: "Banque", type: AccountType.ASSET },
    { code: "571000", name: "Caisse", type: AccountType.ASSET },
    { code: "601000", name: "Achats de marchandises", type: AccountType.EXPENSE },
    { code: "611000", name: "Transports sur achats", type: AccountType.EXPENSE },
    { code: "622000", name: "Locations et charges locatives", type: AccountType.EXPENSE },
    { code: "624000", name: "Entretien et réparations", type: AccountType.EXPENSE },
    { code: "625000", name: "Primes d'assurances", type: AccountType.EXPENSE },
    { code: "626000", name: "Études, recherches et documentation", type: AccountType.EXPENSE },
    { code: "627000", name: "Publicité, publications", type: AccountType.EXPENSE },
    { code: "631000", name: "Frais de télécommunications", type: AccountType.EXPENSE },
    { code: "641000", name: "Charges de personnel", type: AccountType.EXPENSE },
    { code: "661000", name: "Intérêts des emprunts", type: AccountType.EXPENSE },
    { code: "701000", name: "Ventes de marchandises", type: AccountType.REVENUE },
    { code: "706000", name: "Prestations de services", type: AccountType.REVENUE },
    { code: "707000", name: "Produits accessoires", type: AccountType.REVENUE },
  ];
  for (const a of pcg) {
    await prisma.chartOfAccount.upsert({
      where: { organizationId_code: { organizationId: org.id, code: a.code } },
      update: {},
      create: { organizationId: org.id, code: a.code, name: a.name, type: a.type, isSystem: true },
    });
  }
  console.log(`✅ Plan Comptable SYSCOHADA (${pcg.length} comptes)`);

  // ══════════════════════════════════════════════════
  // CATÉGORIES DE DÉPENSES
  // ══════════════════════════════════════════════════

  const categoriesData = [
    { name: "Informatique & Logiciels",  color: "#6366f1", icon: "Monitor",        accountCode: "626000" },
    { name: "Déplacements & Transport",  color: "#f59e0b", icon: "Car",            accountCode: "611000" },
    { name: "Repas & Restauration",      color: "#ef4444", icon: "UtensilsCrossed", accountCode: "627000" },
    { name: "Fournitures de bureau",     color: "#10b981", icon: "Package",        accountCode: "601000" },
    { name: "Marketing & Publicité",     color: "#8b5cf6", icon: "Megaphone",      accountCode: "627000" },
    { name: "Télécommunications",        color: "#06b6d4", icon: "Phone",          accountCode: "631000" },
    { name: "Services externes",         color: "#f97316", icon: "Briefcase",      accountCode: "626000" },
    { name: "Loyers & Locaux",           color: "#84cc16", icon: "Building",       accountCode: "622000" },
    { name: "Formation",                 color: "#ec4899", icon: "BookOpen",       accountCode: "626000" },
    { name: "Autres",                    color: "#94a3b8", icon: "MoreHorizontal", accountCode: "601000", isDefault: true },
  ];
  const createdCats: Record<string, string> = {};
  for (const cat of categoriesData) {
    const c = await prisma.expenseCategory.upsert({
      where: { organizationId_name: { organizationId: org.id, name: cat.name } } as any,
      update: {},
      create: { organizationId: org.id, name: cat.name, color: cat.color, icon: cat.icon, accountCode: cat.accountCode, isDefault: cat.isDefault ?? false },
    });
    createdCats[cat.name] = c.id;
  }
  console.log("✅ Catégories de dépenses créées");

  // ══════════════════════════════════════════════════
  // BANQUE
  // ══════════════════════════════════════════════════

  await prisma.bankAccount.upsert({
    where: { id: "bank-demo-001" },
    update: {},
    create: {
      id: "bank-demo-001",
      organizationId: org.id,
      name: "Compte courant professionnel",
      bankName: "Ecobank Sénégal",
      iban: "SN08 SN012 01201 0123456789012 56",
      bic: "ECOCSNDA",
      currency: "XOF",
      balance: 8450000,
    },
  });
  console.log("✅ Compte bancaire créé (8 450 000 F CFA)");

  // ══════════════════════════════════════════════════
  // CLIENTS
  // ══════════════════════════════════════════════════

  const clientsData = [
    { name: "Orange Sénégal SA",        email: "finance@orange.sn",          phone: "+221 33 869 00 00", city: "Dakar",  country: "SN", vatNumber: "SN-TVA-0001" },
    { name: "Wave Mobile Money",         email: "comptabilite@wave.com",      phone: "+221 77 100 00 00", city: "Dakar",  country: "SN" },
    { name: "SONATEL Group",            email: "daf@sonatel.sn",              phone: "+221 33 839 00 00", city: "Dakar",  country: "SN", vatNumber: "SN-TVA-0002" },
    { name: "BHS Banque de l'Habitat",  email: "direction@bhs.sn",            phone: "+221 33 839 90 00", city: "Dakar",  country: "SN" },
    { name: "Teranga Industries",        email: "achat@teranga.sn",            phone: "+221 33 821 00 00", city: "Thiès",  country: "SN" },
  ];
  const createdCustomers: { id: string; name: string }[] = [];
  for (const c of clientsData) {
    const customer = await prisma.customer.upsert({
      where: { organizationId_email: { organizationId: org.id, email: c.email } },
      update: {},
      create: { organizationId: org.id, ...c },
    });
    createdCustomers.push(customer);
  }
  console.log(`✅ ${createdCustomers.length} clients créés`);

  // ══════════════════════════════════════════════════
  // FOURNISSEURS
  // ══════════════════════════════════════════════════

  await prisma.supplier.upsert({
    where: { organizationId_email: { organizationId: org.id, email: "factures@expresso.sn" } },
    update: {},
    create: { organizationId: org.id, name: "Expresso Télécom", email: "factures@expresso.sn", city: "Dakar", country: "SN" },
  });
  await prisma.supplier.upsert({
    where: { organizationId_email: { organizationId: org.id, email: "aws-billing@amazon.com" } },
    update: {},
    create: { organizationId: org.id, name: "Amazon Web Services", email: "aws-billing@amazon.com", city: "Dublin", country: "IE" },
  });
  console.log("✅ Fournisseurs créés");

  // ══════════════════════════════════════════════════
  // FACTURES
  // ══════════════════════════════════════════════════

  await prisma.invoice.deleteMany({ where: { organizationId: org.id } });

  const invoicesData: Array<{
    number: string; status: InvoiceStatus; customerId: string;
    issueDate: Date; dueDate: Date; paidDate?: Date; items: ItemInput[];
  }> = [
    {
      number: "FAC-2025-001", status: InvoiceStatus.PAID,
      customerId: createdCustomers[0].id,
      issueDate: new Date("2025-01-10"), dueDate: new Date("2025-02-10"), paidDate: new Date("2025-01-28"),
      items: [
        { description: "Développement plateforme e-commerce — Phase 1", quantity: 1, unitPrice: 2500000, taxRate: 18 },
        { description: "Intégration passerelle de paiement Wave", quantity: 1, unitPrice: 750000, taxRate: 18 },
      ],
    },
    {
      number: "FAC-2025-002", status: InvoiceStatus.PAID,
      customerId: createdCustomers[1].id,
      issueDate: new Date("2025-02-01"), dueDate: new Date("2025-03-01"), paidDate: new Date("2025-02-20"),
      items: [
        { description: "Audit sécurité système d'information", quantity: 1, unitPrice: 1800000, taxRate: 18 },
        { description: "Rapport et recommandations", quantity: 1, unitPrice: 200000, taxRate: 18 },
      ],
    },
    {
      number: "FAC-2025-003", status: InvoiceStatus.PAID,
      customerId: createdCustomers[2].id,
      issueDate: new Date("2025-02-15"), dueDate: new Date("2025-03-15"), paidDate: new Date("2025-03-08"),
      items: [
        { description: "Conseil en transformation digitale — Mars", quantity: 15, unitPrice: 120000, taxRate: 18 },
      ],
    },
    {
      number: "FAC-2025-004", status: InvoiceStatus.SENT,
      customerId: createdCustomers[3].id,
      issueDate: new Date("2025-03-01"), dueDate: new Date("2025-04-01"),
      items: [
        { description: "Développement application mobile Android/iOS", quantity: 1, unitPrice: 4500000, taxRate: 18 },
        { description: "Maintenance premier trimestre", quantity: 3, unitPrice: 350000, taxRate: 18 },
      ],
    },
    {
      number: "FAC-2025-005", status: InvoiceStatus.DRAFT,
      customerId: createdCustomers[4].id,
      issueDate: new Date("2025-03-15"), dueDate: new Date("2025-04-15"),
      items: [
        { description: "Formation équipe IT — 3 jours", quantity: 3, unitPrice: 450000, taxRate: 18 },
        { description: "Support post-formation (1 mois)", quantity: 1, unitPrice: 250000, taxRate: 18 },
      ],
    },
    {
      number: "FAC-2025-006", status: InvoiceStatus.OVERDUE,
      customerId: createdCustomers[0].id,
      issueDate: new Date("2025-01-20"), dueDate: new Date("2025-02-20"),
      items: [
        { description: "Développement plateforme e-commerce — Phase 2", quantity: 1, unitPrice: 3200000, taxRate: 18 },
      ],
    },
    {
      number: "FAC-2025-007", status: InvoiceStatus.PAID,
      customerId: createdCustomers[1].id,
      issueDate: new Date("2025-03-05"), dueDate: new Date("2025-04-05"), paidDate: new Date("2025-03-25"),
      items: [
        { description: "Hébergement et maintenance serveurs — T1 2025", quantity: 1, unitPrice: 960000, taxRate: 18 },
      ],
    },
    {
      number: "FAC-2025-008", status: InvoiceStatus.SENT,
      customerId: createdCustomers[2].id,
      issueDate: new Date("2025-03-20"), dueDate: new Date("2025-04-20"),
      items: [
        { description: "Conseil en transformation digitale — Avril", quantity: 15, unitPrice: 120000, taxRate: 18 },
        { description: "Atelier design thinking (2 sessions)", quantity: 2, unitPrice: 600000, taxRate: 18 },
      ],
    },
  ];

  for (const inv of invoicesData) {
    const { rows, subtotal, taxAmount, discountAmount, total } = calc(inv.items);
    const isPaid = inv.status === InvoiceStatus.PAID;
    await prisma.invoice.create({
      data: {
        organizationId: org.id, customerId: inv.customerId, number: inv.number,
        status: inv.status, issueDate: inv.issueDate, dueDate: inv.dueDate,
        paidDate: inv.paidDate ?? null, subtotal, taxAmount, discountAmount, total,
        amountPaid: isPaid ? total : 0, amountDue: isPaid ? 0 : total,
        currency: "XOF", items: { create: rows },
      },
    });
  }
  console.log(`✅ ${invoicesData.length} factures créées`);

  // ══════════════════════════════════════════════════
  // DEVIS
  // ══════════════════════════════════════════════════

  await prisma.quote.deleteMany({ where: { organizationId: org.id } });

  const quotesData: Array<{
    number: string; status: QuoteStatus; customerId: string; subject: string;
    issueDate: Date; expiryDate: Date; items: ItemInput[];
    sentAt?: Date; acceptedAt?: Date; rejectedAt?: Date;
  }> = [
    {
      number: "DEV-2025-0001", status: QuoteStatus.ACCEPTED,
      customerId: createdCustomers[0].id, subject: "Refonte site web institutionnel",
      issueDate: new Date("2025-02-01"), expiryDate: new Date("2025-03-01"),
      sentAt: new Date("2025-02-02"), acceptedAt: new Date("2025-02-15"),
      items: [
        { description: "Design UX/UI maquettes", quantity: 1, unitPrice: 850000, taxRate: 18 },
        { description: "Intégration HTML/CSS responsive", quantity: 1, unitPrice: 1200000, taxRate: 18 },
        { description: "CMS sur mesure", quantity: 1, unitPrice: 650000, taxRate: 18 },
      ],
    },
    {
      number: "DEV-2025-0002", status: QuoteStatus.SENT,
      customerId: createdCustomers[3].id, subject: "Développement ERP bancaire",
      issueDate: new Date("2025-03-10"), expiryDate: new Date("2025-04-10"),
      sentAt: new Date("2025-03-10"),
      items: [
        { description: "Analyse des besoins et architecture", quantity: 1, unitPrice: 1500000, taxRate: 18 },
        { description: "Développement modules comptables", quantity: 1, unitPrice: 5000000, taxRate: 18 },
        { description: "Intégration API BCEAO", quantity: 1, unitPrice: 1200000, taxRate: 18 },
        { description: "Tests et recette", quantity: 1, unitPrice: 800000, taxRate: 18 },
      ],
    },
    {
      number: "DEV-2025-0003", status: QuoteStatus.DRAFT,
      customerId: createdCustomers[4].id, subject: "Formation et accompagnement équipes IT",
      issueDate: new Date("2025-03-20"), expiryDate: new Date("2025-04-20"),
      items: [
        { description: "Audit compétences équipe (10 personnes)", quantity: 1, unitPrice: 400000, taxRate: 18 },
        { description: "Formation Cloud AWS — 5 jours", quantity: 5, unitPrice: 250000, taxRate: 18 },
        { description: "Formation cybersécurité — 3 jours", quantity: 3, unitPrice: 250000, taxRate: 18 },
      ],
    },
    {
      number: "DEV-2025-0004", status: QuoteStatus.REJECTED,
      customerId: createdCustomers[1].id, subject: "Application de livraison en ligne",
      issueDate: new Date("2025-01-15"), expiryDate: new Date("2025-02-15"),
      sentAt: new Date("2025-01-15"), rejectedAt: new Date("2025-02-01"),
      items: [
        { description: "Application mobile iOS + Android", quantity: 1, unitPrice: 7500000, taxRate: 18 },
        { description: "Panel admin web", quantity: 1, unitPrice: 2000000, taxRate: 18 },
      ],
    },
  ];

  for (const q of quotesData) {
    const { rows, subtotal, taxAmount, discountAmount, total } = calc(q.items);
    await prisma.quote.create({
      data: {
        organizationId: org.id, customerId: q.customerId, number: q.number,
        status: q.status, subject: q.subject, issueDate: q.issueDate, expiryDate: q.expiryDate,
        sentAt: q.sentAt ?? null, acceptedAt: q.acceptedAt ?? null, rejectedAt: q.rejectedAt ?? null,
        subtotal, taxAmount, discountAmount, total, currency: "XOF",
        items: { create: rows },
      },
    });
  }
  console.log(`✅ ${quotesData.length} devis créés`);

  // ══════════════════════════════════════════════════
  // FACTURES RÉCURRENTES
  // ══════════════════════════════════════════════════

  await prisma.recurringInvoice.deleteMany({ where: { organizationId: org.id } });

  const recurringData: Array<{
    subject: string; customerId: string; frequency: RecurringFrequency;
    status: RecurringStatus; startDate: Date; nextRunDate: Date;
    lastRunDate?: Date; runCount: number; items: ItemInput[];
  }> = [
    {
      subject: "Maintenance mensuelle serveurs",
      customerId: createdCustomers[1].id, frequency: "MONTHLY", status: "ACTIVE",
      startDate: new Date("2025-01-01"), nextRunDate: new Date("2025-04-01"),
      lastRunDate: new Date("2025-03-01"), runCount: 3,
      items: [
        { description: "Monitoring et supervision serveurs (24/7)", quantity: 1, unitPrice: 450000, taxRate: 18 },
        { description: "Mises à jour sécurité", quantity: 1, unitPrice: 150000, taxRate: 18 },
      ],
    },
    {
      subject: "Abonnement plateforme SaaS CRM",
      customerId: createdCustomers[2].id, frequency: "MONTHLY", status: "ACTIVE",
      startDate: new Date("2025-02-01"), nextRunDate: new Date("2025-04-01"),
      lastRunDate: new Date("2025-03-01"), runCount: 2,
      items: [
        { description: "Licence logiciel CRM — 20 utilisateurs", quantity: 20, unitPrice: 25000, taxRate: 18 },
      ],
    },
    {
      subject: "Conseil trimestriel stratégie IT",
      customerId: createdCustomers[0].id, frequency: "QUARTERLY", status: "ACTIVE",
      startDate: new Date("2025-01-01"), nextRunDate: new Date("2025-04-01"),
      lastRunDate: new Date("2025-01-01"), runCount: 1,
      items: [
        { description: "Séance de conseil stratégique (2 jours)", quantity: 2, unitPrice: 750000, taxRate: 18 },
        { description: "Rapport et feuille de route", quantity: 1, unitPrice: 250000, taxRate: 18 },
      ],
    },
    {
      subject: "Hébergement annuel site web",
      customerId: createdCustomers[4].id, frequency: "YEARLY", status: "PAUSED",
      startDate: new Date("2024-06-01"), nextRunDate: new Date("2025-06-01"),
      lastRunDate: new Date("2024-06-01"), runCount: 1,
      items: [
        { description: "Hébergement VPS dédié (12 mois)", quantity: 1, unitPrice: 960000, taxRate: 18 },
        { description: "Nom de domaine + SSL", quantity: 1, unitPrice: 40000, taxRate: 18 },
      ],
    },
  ];

  for (const r of recurringData) {
    const { rows, subtotal, taxAmount, discountAmount, total } = calc(r.items);
    await prisma.recurringInvoice.create({
      data: {
        organizationId: org.id, customerId: r.customerId, subject: r.subject,
        frequency: r.frequency, status: r.status, startDate: r.startDate,
        nextRunDate: r.nextRunDate, lastRunDate: r.lastRunDate ?? null, runCount: r.runCount,
        currency: "XOF", subtotal, taxAmount, discountAmount, total,
        items: { create: rows },
      },
    });
  }
  console.log(`✅ ${recurringData.length} factures récurrentes créées`);

  // ══════════════════════════════════════════════════
  // DÉPENSES
  // ══════════════════════════════════════════════════

  await prisma.expense.deleteMany({ where: { organizationId: org.id } });

  const expensesData = [
    { title: "Abonnement AWS — Hébergement",         amount: 185000, taxRate: 18, cat: "Informatique & Logiciels",  date: new Date("2025-01-05"), status: ExpenseStatus.APPROVED },
    { title: "Abonnement GitHub Teams",              amount:  42000, taxRate: 18, cat: "Informatique & Logiciels",  date: new Date("2025-01-05"), status: ExpenseStatus.APPROVED },
    { title: "Loyer bureaux — Janvier",              amount: 750000, taxRate:  0, cat: "Loyers & Locaux",           date: new Date("2025-01-03"), status: ExpenseStatus.APPROVED },
    { title: "Déjeuner client — Orange Sénégal",     amount:  85000, taxRate: 18, cat: "Repas & Restauration",      date: new Date("2025-01-12"), status: ExpenseStatus.APPROVED },
    { title: "Billets d'avion Dakar-Abidjan",        amount: 420000, taxRate:  0, cat: "Déplacements & Transport",  date: new Date("2025-01-20"), status: ExpenseStatus.APPROVED },
    { title: "Publicité LinkedIn Ads — Janvier",     amount: 150000, taxRate: 18, cat: "Marketing & Publicité",     date: new Date("2025-01-25"), status: ExpenseStatus.APPROVED },
    { title: "Loyer bureaux — Février",              amount: 750000, taxRate:  0, cat: "Loyers & Locaux",           date: new Date("2025-02-03"), status: ExpenseStatus.APPROVED },
    { title: "Fournitures de bureau",                amount:  38500, taxRate: 18, cat: "Fournitures de bureau",     date: new Date("2025-02-08"), status: ExpenseStatus.APPROVED },
    { title: "Abonnement Figma Professional",        amount:  28000, taxRate: 18, cat: "Informatique & Logiciels",  date: new Date("2025-02-10"), status: ExpenseStatus.APPROVED },
    { title: "Formation React Advanced",             amount:  35000, taxRate: 18, cat: "Formation",                 date: new Date("2025-02-15"), status: ExpenseStatus.APPROVED },
    { title: "Forfait mobile entreprise x3",         amount:  90000, taxRate: 18, cat: "Télécommunications",        date: new Date("2025-02-01"), status: ExpenseStatus.APPROVED },
    { title: "Loyer bureaux — Mars",                 amount: 750000, taxRate:  0, cat: "Loyers & Locaux",           date: new Date("2025-03-03"), status: ExpenseStatus.APPROVED },
    { title: "Abonnement AWS — Hébergement",         amount: 192000, taxRate: 18, cat: "Informatique & Logiciels",  date: new Date("2025-03-05"), status: ExpenseStatus.APPROVED },
    { title: "Taxi aéroport Dakar",                  amount:  15000, taxRate:  0, cat: "Déplacements & Transport",  date: new Date("2025-03-10"), status: ExpenseStatus.PENDING },
    { title: "Déjeuner d'affaires — BHS",            amount: 120000, taxRate: 18, cat: "Repas & Restauration",      date: new Date("2025-03-15"), status: ExpenseStatus.PENDING },
    { title: "Consultant juridique — contrat",       amount: 350000, taxRate: 18, cat: "Services externes",         date: new Date("2025-03-18"), status: ExpenseStatus.PENDING },
    { title: "Publicité Google Ads — Mars",          amount: 200000, taxRate: 18, cat: "Marketing & Publicité",     date: new Date("2025-03-20"), status: ExpenseStatus.PENDING },
    { title: "Imprimante laser couleur",             amount: 285000, taxRate: 18, cat: "Fournitures de bureau",     date: new Date("2025-03-22"), status: ExpenseStatus.PENDING },
  ];

  for (const exp of expensesData) {
    await prisma.expense.create({
      data: {
        organizationId: org.id, title: exp.title, amount: exp.amount,
        taxAmount: r2(exp.amount * (exp.taxRate / 100)), taxRate: exp.taxRate,
        categoryId: createdCats[exp.cat], date: exp.date, status: exp.status, currency: "XOF",
      },
    });
  }
  console.log(`✅ ${expensesData.length} dépenses créées`);

  // ══════════════════════════════════════════════════
  // BONS DE LIVRAISON
  // ══════════════════════════════════════════════════

  await prisma.deliveryNote.deleteMany({ where: { organizationId: org.id } });

  const blData = [
    {
      number: "BL-2026-0001",
      customerId: createdCustomers[0].id, // Orange SN
      status: "DELIVERED" as const,
      issueDate: new Date("2026-01-15"),
      deliveryDate: new Date("2026-01-18"),
      deliveredAt: new Date("2026-01-18"),
      sentAt: new Date("2026-01-15"),
      reference: "BC-2026-001",
      shippingAddress: "Immeuble Orange, Av. Cheikh Anta Diop, Dakar",
      items: [
        { description: "Serveurs Dell PowerEdge R750", orderedQty: 3, deliveredQty: 3, unit: "unité" },
        { description: "Câbles réseau Cat6 (10m)", orderedQty: 20, deliveredQty: 20, unit: "pcs" },
      ],
    },
    {
      number: "BL-2026-0002",
      customerId: createdCustomers[1].id, // Wave
      status: "SENT" as const,
      issueDate: new Date("2026-02-10"),
      deliveryDate: new Date("2026-02-14"),
      sentAt: new Date("2026-02-10"),
      reference: "PO-WAVE-0041",
      items: [
        { description: "Licences logiciel comptabilité (annuel)", orderedQty: 10, deliveredQty: 10, unit: "licence" },
        { description: "Formation utilisateurs (jours)", orderedQty: 5, deliveredQty: 4, unit: "jour", notes: "1 session reportée" },
      ],
    },
    {
      number: "BL-2026-0003",
      customerId: createdCustomers[2].id, // SONATEL
      status: "DRAFT" as const,
      issueDate: new Date("2026-03-05"),
      deliveryDate: new Date("2026-03-12"),
      reference: "BC-SONATEL-2026-03",
      items: [
        { description: "Bornes WiFi entreprise Cisco", orderedQty: 15, deliveredQty: 0, unit: "unité" },
        { description: "Câblage et installation", orderedQty: 1, deliveredQty: 0, unit: "forfait" },
      ],
    },
    {
      number: "BL-2026-0004",
      customerId: createdCustomers[3].id, // BHS
      status: "DELIVERED" as const,
      issueDate: new Date("2026-01-28"),
      deliveryDate: new Date("2026-01-30"),
      deliveredAt: new Date("2026-01-30"),
      sentAt: new Date("2026-01-28"),
      notes: "Livraison effectuée sans incident",
      items: [
        { description: "Imprimantes HP LaserJet", orderedQty: 4, deliveredQty: 4, unit: "unité" },
        { description: "Cartouches d'encre HP (lot)", orderedQty: 8, deliveredQty: 8, unit: "lot" },
        { description: "Maintenance préventive", orderedQty: 1, deliveredQty: 1, unit: "forfait" },
      ],
    },
  ];

  for (const bl of blData) {
    const { items, ...blFields } = bl;
    await prisma.deliveryNote.create({
      data: {
        organizationId: org.id,
        ...blFields,
        items: {
          create: items.map((it, i) => ({
            description: it.description,
            orderedQty: it.orderedQty,
            deliveredQty: it.deliveredQty,
            unit: it.unit ?? null,
            notes: (it as { notes?: string }).notes ?? null,
            order: i,
          })),
        },
      },
    });
  }
  console.log(`✅ ${blData.length} bons de livraison créés`);

  // ══════════════════════════════════════════════════
  // RÉSUMÉ
  // ══════════════════════════════════════════════════

  console.log("\n🎉 Seed terminé avec succès !");
  console.log("\n📧 Comptes de connexion :");
  console.log("   Démo :  demo@nextcrm.io  /  Demo@123!");
  console.log("   Admin : admin@nextcrm.io /  Admin@123!");
  console.log("\n📊 Données créées :");
  console.log(`   ${createdCustomers.length} clients · ${invoicesData.length} factures · ${quotesData.length} devis`);
  console.log(`   ${recurringData.length} factures récurrentes · ${expensesData.length} dépenses`);
  console.log(`   ${blData.length} bons de livraison`);
  console.log("   Compte bancaire : 8 450 000 F CFA");
}

main()
  .catch((e) => { console.error("❌ Erreur :", e); process.exit(1); })
  .finally(() => prisma.$disconnect());
