import { PrismaClient } from "@prisma/client";
import bcrypt from "bcryptjs";

const prisma = new PrismaClient();

const ALL = ["view", "create", "edit", "delete"];
const VIEW = ["view"];

function permissions(map: Record<string, string[]>) {
  return JSON.stringify(map);
}

async function main() {
  await prisma.expense.deleteMany();
  await prisma.storeSaleLine.deleteMany();
  await prisma.storeSale.deleteMany();
  await prisma.storeStock.deleteMany();
  await prisma.supplierPayment.deleteMany();
  await prisma.purchaseLine.deleteMany();
  await prisma.purchase.deleteMany();
  await prisma.supplier.deleteMany();
  await prisma.notification.deleteMany();
  await prisma.cashRemittance.deleteMany();
  await prisma.payment.deleteMany();
  await prisma.deliveryNoteLine.deleteMany();
  await prisma.deliveryNote.deleteMany();
  await prisma.proformaLine.deleteMany();
  await prisma.proforma.deleteMany();
  await prisma.roundStop.deleteMany();
  await prisma.deliveryRound.deleteMany();
  await prisma.orderLine.deleteMany();
  await prisma.order.deleteMany();
  await prisma.priceChangeLog.deleteMany();
  await prisma.priceTier.deleteMany();
  await prisma.priceList.deleteMany();
  await prisma.stockMove.deleteMany();
  await prisma.product.deleteMany();
  await prisma.category.deleteMany();
  await prisma.accountMinimum.deleteMany();
  await prisma.customer.deleteMany();
  await prisma.deliveryAgent.deleteMany();
  await prisma.vehicle.deleteMany();
  await prisma.activityLog.deleteMany();
  await prisma.user.deleteMany();
  await prisma.role.deleteMany();
  await prisma.companySettings.deleteMany();

  const superAdmin = await prisma.role.create({
    data: {
      name: "Super Admin",
      permissions: permissions({
        users: ALL, activity: VIEW, customers: ALL, products: ALL, purchases: ALL, store: ALL, pricing: ALL,
        orders: ALL, invoices: ALL, settings: ALL, rounds: ALL, fleet: ALL,
        payments: ALL, statistics: VIEW, analysis: ALL, notifications: VIEW,
      }),
    },
  });
  const sales = await prisma.role.create({
    data: {
      name: "Sales Manager",
      permissions: permissions({
        users: VIEW, activity: VIEW, customers: ALL, products: VIEW, purchases: VIEW, store: ALL, pricing: ALL,
        orders: ALL, invoices: ALL, settings: VIEW, rounds: VIEW, fleet: VIEW,
        payments: VIEW, statistics: VIEW, analysis: ALL, notifications: VIEW,
      }),
    },
  });
  const warehouse = await prisma.role.create({
    data: {
      name: "Warehouse Agent",
      permissions: permissions({
        users: [], activity: VIEW, customers: VIEW, products: ALL, purchases: ALL, store: ["view", "create", "edit"], pricing: VIEW,
        orders: ["view", "edit"], invoices: ["view", "create", "edit"], settings: [],
        rounds: ["view", "edit"], fleet: VIEW, payments: [], statistics: VIEW,
        analysis: VIEW, notifications: VIEW,
      }),
    },
  });
  const accountant = await prisma.role.create({
    data: {
      name: "Accountant",
      permissions: permissions({
        users: [], activity: VIEW, customers: VIEW, products: VIEW, purchases: ["view", "create", "edit"], store: ALL, pricing: VIEW,
        orders: VIEW, invoices: ALL, settings: ["view", "edit"], rounds: VIEW,
        fleet: VIEW, payments: ALL, statistics: VIEW, analysis: VIEW, notifications: VIEW,
      }),
    },
  });
  const dispatcher = await prisma.role.create({
    data: {
      name: "Dispatcher",
      permissions: permissions({
        users: [], activity: VIEW, customers: VIEW, products: VIEW, purchases: VIEW, store: VIEW, pricing: VIEW,
        orders: ["view", "edit"], invoices: VIEW, settings: [], rounds: ALL,
        fleet: ALL, payments: ["view", "create"], statistics: VIEW, analysis: VIEW,
        notifications: VIEW,
      }),
    },
  });

  const password = await bcrypt.hash("absher123", 10);
  const users = await Promise.all([
    prisma.user.create({ data: { firstName: "Amel", lastName: "Benaissa", phone: "0550000001", email: "admin@absher.local", passwordHash: password, roleId: superAdmin.id } }),
    prisma.user.create({ data: { firstName: "Karim", lastName: "Hadj", phone: "0550000002", email: "sales@absher.local", passwordHash: password, roleId: sales.id } }),
    prisma.user.create({ data: { firstName: "Nour", lastName: "Mansouri", phone: "0550000003", email: "warehouse@absher.local", passwordHash: password, roleId: warehouse.id } }),
    prisma.user.create({ data: { firstName: "Lina", lastName: "Khelifi", phone: "0550000004", email: "accounts@absher.local", passwordHash: password, roleId: accountant.id } }),
    prisma.user.create({ data: { firstName: "Yacine", lastName: "Cherif", phone: "0550000005", email: "dispatch@absher.local", passwordHash: password, roleId: dispatcher.id } }),
  ]);
  const admin = users[0];

  await prisma.companySettings.create({
    data: {
      id: "company",
      companyName: "Absher Distribution",
      address: "12 Rue Didouche Mourad, Algiers",
      phone: "021 00 00 00",
      email: "ops@absher.local",
      businessReg: "16/00-1234567B16",
      taxId: "001612345678901",
      statisticalId: "16-1234567",
      taxArticle: "A-4410",
      bankInfo: "CPA 004 00123 0000123456 78",
      logoText: "ABSHER",
      stampText: "COMPANY STAMP",
      vatRate: 19,
      stampAmount: 100,
      proformaPrefix: "PF-",
      proformaNext: 1004,
      deliveryPrefix: "BL-",
      deliveryNext: 2004,
      terms: "Payment due within 15 days. Goods remain the property of Absher Distribution until full payment.",
    },
  });

  await prisma.accountMinimum.createMany({
    data: [
      { accountType: "RETAIL", minOrderAmount: 2500 },
      { accountType: "SEMI_WHOLESALE", minOrderAmount: 12000 },
      { accountType: "WHOLESALE", minOrderAmount: 35000 },
    ],
  });

  const [oils, dairy, dry] = await Promise.all([
    prisma.category.create({ data: { name: "Oils & fats" } }),
    prisma.category.create({ data: { name: "Dairy" } }),
    prisma.category.create({ data: { name: "Dry goods" } }),
  ]);

  const products = await Promise.all([
    prisma.product.create({ data: { name: "Sunflower oil 5L", reference: "OIL-5L", barcode: "6130000100015", packaging: "SINGLE", unitsPerCarton: 1, imageUrl: "/products/oil-5l.svg", description: "Refined sunflower oil, 5 litre jerrycan.", categoryId: oils.id, quantity: 420, retailPrice: 1450, semiWholesalePrice: 1320, wholesalePrice: 1180 } }),
    prisma.product.create({ data: { name: "Olive oil 1L", reference: "OLV-1L", barcode: "6130000100022", packaging: "SINGLE", unitsPerCarton: 1, imageUrl: "/products/olv-1l.svg", description: "Extra virgin olive oil.", categoryId: oils.id, quantity: 180, retailPrice: 2100, semiWholesalePrice: 1890, wholesalePrice: 1650 } }),
    prisma.product.create({ data: { name: "UHT milk 1L", reference: "MLK-1L", barcode: "6130000100039", packaging: "CARTON", unitsPerCarton: 12, imageUrl: "/products/mlk-1l.svg", description: "Long-life whole milk.", categoryId: dairy.id, quantity: 900, retailPrice: 180, semiWholesalePrice: 160, wholesalePrice: 140 } }),
    prisma.product.create({ data: { name: "Yogurt 125g x12", reference: "YOG-12", barcode: "6130000100046", packaging: "CARTON", unitsPerCarton: 12, imageUrl: "/products/yog-12.svg", description: "Natural yogurt multipack.", categoryId: dairy.id, quantity: 260, retailPrice: 980, semiWholesalePrice: 860, wholesalePrice: 740 } }),
    prisma.product.create({ data: { name: "Couscous 5kg", reference: "COU-5K", barcode: "6130000100053", packaging: "SINGLE", unitsPerCarton: 1, imageUrl: "/products/cou-5k.svg", description: "Medium grain couscous.", categoryId: dry.id, quantity: 310, retailPrice: 1250, semiWholesalePrice: 1100, wholesalePrice: 940 } }),
    prisma.product.create({ data: { name: "Semolina 25kg", reference: "SEM-25", barcode: "6130000100060", packaging: "SINGLE", unitsPerCarton: 1, imageUrl: "/products/sem-25.svg", description: "Fine semolina sack.", categoryId: dry.id, quantity: 140, retailPrice: 4200, semiWholesalePrice: 3900, wholesalePrice: 3550 } }),
  ]);

  // Each account type buys within its own quantity window; the price follows the account type.
  const windows = { RETAIL: [1, 20], SEMI_WHOLESALE: [10, 100], WHOLESALE: [20, 9999] } as const;
  for (const product of products) {
    for (const accountType of ["RETAIL", "SEMI_WHOLESALE", "WHOLESALE"] as const) {
      const [minQty, maxQty] = windows[accountType];
      await prisma.priceList.create({
        data: { productId: product.id, accountType, active: true, minQty, maxQty },
      });
    }
    await prisma.priceChangeLog.create({
      data: { productId: product.id, accountType: "RETAIL", previousPrice: product.retailPrice + 40, newPrice: product.retailPrice, userId: admin.id },
    });
  }

  const customers = await Promise.all([
    prisma.customer.create({ data: { firstName: "Said", lastName: "Bouaziz", phone: "0551111001", email: "said.shop@example.com", accountType: "RETAIL", status: "ACTIVE", region: "Algiers", address: "Bab El Oued market stall 14", latitude: 36.79, longitude: 3.05, companyName: "Said Mini Market", billingAddress: "Bab El Oued, Algiers", businessReg: "16/00-111", taxId: "0016111", statisticalId: "16-111", taxArticle: "A-1", creditLimit: 25000 } }),
    prisma.customer.create({ data: { firstName: "Fatima", lastName: "Zerrouki", phone: "0551111002", email: "fatima.semi@example.com", accountType: "SEMI_WHOLESALE", status: "ACTIVE", region: "Blida", address: "Rue Boudjemaa, Blida", latitude: 36.47, longitude: 2.83, companyName: "Zerrouki Depot", billingAddress: "Blida centre", businessReg: "09/00-222", taxId: "0009222", statisticalId: "09-222", taxArticle: "A-2", creditLimit: 80000 } }),
    prisma.customer.create({ data: { firstName: "Omar", lastName: "Benali", phone: "0551111003", email: "omar.wholesale@example.com", accountType: "WHOLESALE", status: "ACTIVE", region: "Oran", address: "Zone industrielle, Oran", latitude: 35.7, longitude: -0.64, companyName: "Benali Cash & Carry", billingAddress: "Oran ZI", businessReg: "31/00-333", taxId: "0031333", statisticalId: "31-333", taxArticle: "A-3", creditLimit: 250000 } }),
    prisma.customer.create({ data: { firstName: "Nadia", lastName: "Mebarki", phone: "0551111004", email: "nadia.pending@example.com", accountType: "RETAIL", status: "PENDING", region: "Constantine", address: "Sidi Mabrouk, Constantine", companyName: "Nadia Grocery", creditLimit: 15000 } }),
    prisma.customer.create({ data: { firstName: "Hakim", lastName: "Toumi", phone: "0551111005", email: "hakim.inactive@example.com", accountType: "SEMI_WHOLESALE", status: "INACTIVE", region: "Setif", address: "Setif centre", companyName: "Toumi Store", creditLimit: 40000 } }),
  ]);

  const van = await prisma.vehicle.create({ data: { type: "Van", make: "Renault Master", registration: "16-123-16", capacity: "1.5 t" } });
  const truck = await prisma.vehicle.create({ data: { type: "Truck", make: "Isuzu NPR", registration: "16-456-16", capacity: "4 t" } });
  const agents = await Promise.all([
    prisma.deliveryAgent.create({ data: { firstName: "Bilal", lastName: "Ait", phone: "0552000001", region: "Algiers", address: "Depot Bab Ezzouar, Algiers", latitude: 36.721, longitude: 3.185, vehicleId: van.id } }),
    prisma.deliveryAgent.create({ data: { firstName: "Sofiane", lastName: "Dahmani", phone: "0552000002", region: "Oran", address: "Zone industrielle, Oran", latitude: 35.691, longitude: -0.642, vehicleId: truck.id } }),
  ]);

  const oil = products[0];
  const milk = products[2];
  const couscous = products[4];

  const daysAgo = (n: number) => new Date(Date.now() - n * 86400000);

  const orderA = await prisma.order.create({
    data: {
      reference: "ORD-1001",
      customerId: customers[0].id,
      status: "DELIVERED",
      region: "Algiers",
      agentId: agents[0].id,
      total: 1450 * 8 + 180 * 20,
      createdAt: daysAgo(25),
      createdById: admin.id,
      lines: {
        create: [
          { productId: oil.id, quantity: 8, unitPrice: 1450, deliveredQty: 8 },
          { productId: milk.id, quantity: 20, unitPrice: 180, deliveredQty: 20 },
        ],
      },
    },
  });
  const orderB = await prisma.order.create({
    data: {
      reference: "ORD-1002",
      customerId: customers[1].id,
      status: "SCHEDULED",
      region: "Blida",
      agentId: agents[0].id,
      total: 1320 * 12 + 1100 * 10,
      createdAt: daysAgo(1),
      createdById: users[1].id,
      lines: {
        create: [
          { productId: oil.id, quantity: 12, unitPrice: 1320, deliveredQty: 0 },
          { productId: couscous.id, quantity: 10, unitPrice: 1100, deliveredQty: 0 },
        ],
      },
    },
  });
  const orderC = await prisma.order.create({
    data: {
      reference: "ORD-1003",
      customerId: customers[2].id,
      status: "NEW",
      region: "Oran",
      total: 1180 * 40 + 140 * 80 + 940 * 20,
      createdAt: daysAgo(0),
      createdById: users[1].id,
      lines: {
        create: [
          { productId: oil.id, quantity: 40, unitPrice: 1180, deliveredQty: 0 },
          { productId: milk.id, quantity: 80, unitPrice: 140, deliveredQty: 0 },
          { productId: couscous.id, quantity: 20, unitPrice: 940, deliveredQty: 0 },
        ],
      },
    },
  });
  await prisma.order.create({
    data: {
      reference: "ORD-1004",
      customerId: customers[0].id,
      status: "ACCEPTED",
      region: "Algiers",
      total: 1450 * 4,
      createdAt: daysAgo(0),
      createdById: users[1].id,
      lines: { create: [{ productId: oil.id, quantity: 4, unitPrice: 1450, deliveredQty: 0 }] },
    },
  });

  const round = await prisma.deliveryRound.create({
    data: {
      kind: "DELIVERY",
      date: new Date(),
      agentId: agents[0].id,
      vehicleId: van.id,
      region: "Algiers / Blida",
      status: "PLANNED",
      stops: {
        create: [
          { orderId: orderB.id, sequence: 1, status: "PENDING" },
        ],
      },
    },
  });
  const vanRound = await prisma.deliveryRound.create({
    data: {
      kind: "PROSPECTING",
      date: new Date(),
      agentId: agents[1].id,
      vehicleId: truck.id,
      region: "Oran west",
      notes: "Propose oil and milk to small shops. Return leftover stock tonight.",
      status: "IN_PROGRESS",
      loads: {
        create: [
          { productId: oil.id, loadedQty: 30, returnedQty: 0 },
          { productId: milk.id, loadedQty: 60, returnedQty: 0 },
        ],
      },
    },
  });

  const pf = await prisma.proforma.create({
    data: {
      number: "PF-01001",
      orderId: orderA.id,
      customerId: customers[0].id,
      status: "VALIDATED",
      discount: 0,
      amountBeforeTax: orderA.total,
      vatAmount: orderA.total * 0.19,
      stampAmount: 100,
      total: orderA.total * 1.19 + 100,
      totalInWords: "Eighteen thousand two hundred twenty-six dinars",
      validatedAt: daysAgo(11),
      sentToApp: true,
      lines: {
        create: [
          { productId: oil.id, quantity: 8, unitPrice: 1450, lineAmount: 11600 },
          { productId: milk.id, quantity: 20, unitPrice: 180, lineAmount: 3600 },
        ],
      },
    },
  });
  await prisma.proforma.create({
    data: {
      number: "PF-01002",
      orderId: orderC.id,
      customerId: customers[2].id,
      status: "DRAFT",
      discount: 1000,
      amountBeforeTax: orderC.total - 1000,
      vatAmount: (orderC.total - 1000) * 0.19,
      stampAmount: 100,
      total: (orderC.total - 1000) * 1.19 + 100,
      totalInWords: "Draft total",
      lines: {
        create: [
          { productId: oil.id, quantity: 40, unitPrice: 1180, lineAmount: 47200 },
          { productId: milk.id, quantity: 80, unitPrice: 140, lineAmount: 11200 },
          { productId: couscous.id, quantity: 20, unitPrice: 940, lineAmount: 18800 },
        ],
      },
    },
  });

  const note = await prisma.deliveryNote.create({
    data: {
      number: "BL-02001",
      orderId: orderA.id,
      customerId: customers[0].id,
      roundId: null,
      agentId: agents[0].id,
      vehicleId: van.id,
      status: "VALIDATED",
      total: orderA.total,
      sentToApp: true,
      createdAt: daysAgo(22),
      lines: {
        create: [
          { productId: oil.id, quantity: 8, unitPrice: 1450, lineAmount: 11600 },
          { productId: milk.id, quantity: 20, unitPrice: 180, lineAmount: 3600 },
        ],
      },
    },
  });

  await prisma.payment.create({
    data: {
      customerId: customers[0].id,
      amount: 10000,
      method: "CASH",
      agentId: agents[0].id,
      documentRef: "REC-01",
      deliveryNoteId: note.id,
      orderId: orderA.id,
      createdAt: daysAgo(10),
    },
  });
  await prisma.cashRemittance.create({
    data: { agentId: agents[0].id, amount: 8000, date: daysAgo(9), documentRef: "REM-01" },
  });

  // ---- Suppliers and purchases
  const [cevital, safina] = await Promise.all([
    prisma.supplier.create({ data: { name: "Cevital Agro", contactName: "Rachid Mansour", phone: "0560100100", email: "ventes@cevital.example", address: "Bejaia, zone portuaire", businessReg: "06/00-0101010", taxId: "000606010101010" } }),
    prisma.supplier.create({ data: { name: "Safina Semoulerie", contactName: "Leila Haddad", phone: "0560200200", email: "commandes@safina.example", address: "Setif, zone industrielle", businessReg: "19/00-0202020", taxId: "001919020202020" } }),
  ]);
  const semolina = products[5];
  const yogurt = products[3];
  const oilCost = 1000;
  const milkCost = 110;
  const received = await prisma.purchase.create({
    data: {
      reference: "ACH-01001",
      supplierId: cevital.id,
      date: daysAgo(30),
      status: "RECEIVED",
      invoiceRef: "CEV-2026-4471",
      receivedAt: daysAgo(30),
      total: 200 * oilCost + 400 * milkCost,
      createdById: admin.id,
      createdAt: daysAgo(31),
      lines: {
        create: [
          { productId: oil.id, quantity: 200, unitCost: oilCost, lineAmount: 200 * oilCost },
          { productId: milk.id, quantity: 400, unitCost: milkCost, lineAmount: 400 * milkCost },
        ],
      },
    },
  });
  await prisma.purchase.create({
    data: {
      reference: "ACH-01002",
      supplierId: safina.id,
      date: daysAgo(1),
      status: "DRAFT",
      invoiceRef: "SAF-889",
      total: 100 * 800 + 50 * 3000,
      notes: "Delivery expected Thursday.",
      createdById: users[2].id,
      lines: {
        create: [
          { productId: couscous.id, quantity: 100, unitCost: 800, lineAmount: 100 * 800 },
          { productId: semolina.id, quantity: 50, unitCost: 3000, lineAmount: 50 * 3000 },
        ],
      },
    },
  });
  await prisma.supplierPayment.create({
    data: { supplierId: cevital.id, purchaseId: received.id, amount: 150000, method: "TRANSFER", date: daysAgo(25), reference: "VIR-5521" },
  });
  const costs: Record<string, number> = { "OIL-5L": oilCost, "MLK-1L": milkCost, "OLV-1L": 1400, "YOG-12": 600, "COU-5K": 800, "SEM-25": 3000 };
  for (const product of products) {
    await prisma.product.update({ where: { id: product.id }, data: { costPrice: costs[product.reference] ?? 0 } });
  }

  // ---- Stock ledger, oldest first, each line carrying the balance after it.
  const balances = new Map<string, number>();
  const ledger: Array<{ productId: string; delta: number; type: string; reason: string; at: Date; reference?: string; sourceId?: string; unitCost?: number }> = [];
  for (const product of products) {
    const purchasedLater = product.id === oil.id ? 200 : product.id === milk.id ? 400 : 0;
    ledger.push({ productId: product.id, delta: product.quantity - purchasedLater, type: "OPENING", reason: "Opening stock", at: daysAgo(40), unitCost: costs[product.reference] });
  }
  ledger.push({ productId: oil.id, delta: 200, type: "PURCHASE", reason: "Purchase ACH-01001", reference: "CEV-2026-4471", sourceId: received.id, unitCost: oilCost, at: daysAgo(30) });
  ledger.push({ productId: milk.id, delta: 400, type: "PURCHASE", reason: "Purchase ACH-01001", reference: "CEV-2026-4471", sourceId: received.id, unitCost: milkCost, at: daysAgo(30) });
  ledger.push({ productId: oil.id, delta: -8, type: "SALE", reason: "Sale BL-02001", reference: "BL-02001", sourceId: note.id, unitCost: 1450, at: daysAgo(22) });
  ledger.push({ productId: milk.id, delta: -20, type: "SALE", reason: "Sale BL-02001", reference: "BL-02001", sourceId: note.id, unitCost: 180, at: daysAgo(22) });
  ledger.push({ productId: yogurt.id, delta: -4, type: "LOSS", reason: "Broken cartons in the cold room", at: daysAgo(5) });
  ledger.push({ productId: oil.id, delta: -30, type: "TRUCK_LOAD", reason: "Truck load Oran west", reference: "Oran west", sourceId: vanRound.id, at: daysAgo(0) });
  ledger.push({ productId: milk.id, delta: -60, type: "TRUCK_LOAD", reason: "Truck load Oran west", reference: "Oran west", sourceId: vanRound.id, at: daysAgo(0) });
  ledger.sort((a, b) => a.at.getTime() - b.at.getTime());
  for (const line of ledger) {
    const balance = (balances.get(line.productId) ?? 0) + line.delta;
    balances.set(line.productId, balance);
    await prisma.stockMove.create({
      data: {
        productId: line.productId,
        delta: line.delta,
        type: line.type,
        reason: line.reason,
        reference: line.reference,
        sourceId: line.sourceId,
        unitCost: line.unitCost,
        balanceAfter: balance,
        userId: line.type === "PURCHASE" || line.type === "LOSS" ? users[2].id : admin.id,
        createdAt: line.at,
      },
    });
  }
  for (const [productId, quantity] of balances) {
    await prisma.product.update({ where: { id: productId }, data: { quantity } });
  }

  // ---- Internal store: shelf stock taken from the warehouse, counter sales, expenses
  const shelf = [
    { product: oil, quantity: 20 },
    { product: milk, quantity: 60 },
    { product: yogurt, quantity: 24 },
  ];
  for (const row of shelf) {
    const balance = (balances.get(row.product.id) ?? 0) - row.quantity;
    balances.set(row.product.id, balance);
    await prisma.stockMove.create({
      data: {
        productId: row.product.id,
        delta: -row.quantity,
        type: "STORE_TRANSFER",
        reason: "Moved to the internal store",
        balanceAfter: balance,
        userId: users[3].id,
        createdAt: daysAgo(3),
      },
    });
    await prisma.product.update({ where: { id: row.product.id }, data: { quantity: balance } });
    await prisma.storeStock.create({ data: { productId: row.product.id, quantity: row.quantity } });
  }

  const counterSales = [
    { number: "BV-01001", at: daysAgo(2), buyer: "Walk-in", method: "CASH", lines: [{ product: oil, qty: 2 }, { product: milk, qty: 6 }] },
    { number: "BV-01002", at: daysAgo(0), buyer: "Hocine B.", method: "CASH", lines: [{ product: yogurt, qty: 3 }] },
  ];
  for (const sale of counterSales) {
    const lines = sale.lines.map((line) => ({
      productId: line.product.id,
      quantity: line.qty,
      unitPrice: line.product.retailPrice,
      lineAmount: line.qty * line.product.retailPrice,
    }));
    const total = lines.reduce((sum, line) => sum + line.lineAmount, 0);
    await prisma.storeSale.create({
      data: {
        number: sale.number,
        createdAt: sale.at,
        buyerName: sale.buyer,
        total,
        paidAmount: total,
        method: sale.method,
        userId: users[3].id,
        lines: { create: lines },
      },
    });
    for (const line of sale.lines) {
      await prisma.storeStock.update({ where: { productId: line.product.id }, data: { quantity: { decrement: line.qty } } });
    }
  }

  await prisma.expense.createMany({
    data: [
      { date: daysAgo(20), category: "RENT", label: "Shop rent, September", amount: 45000, method: "TRANSFER", reference: "VIR-3301", userId: admin.id },
      { date: daysAgo(12), category: "UTILITIES", label: "Electricity and water", amount: 7800, method: "CASH", userId: users[3].id },
      { date: daysAgo(6), category: "SUPPLIES", label: "Receipt rolls and bags", amount: 2400, method: "CASH", userId: users[3].id },
      { date: daysAgo(2), category: "SALARIES", label: "Counter assistant, week 39", amount: 12000, method: "CASH", userId: admin.id },
    ],
  });

  await prisma.notification.createMany({
    data: [
      { audience: "MANAGEMENT", userId: admin.id, type: "NEW_ORDER", title: "New order ORD-1003", body: "Omar Benali placed a wholesale order." },
      { audience: "CUSTOMER", customerId: customers[0].id, type: "PAYMENT", title: "Payment recorded", body: "A cash payment of 10,000 DZD was recorded." },
      { audience: "CUSTOMER", customerId: customers[3].id, type: "ACCOUNT", title: "Account under review", body: "Your retail account is pending acceptance." },
    ],
  });

  await prisma.activityLog.createMany({
    data: [
      { userId: admin.id, department: "customers", operation: "create", item: "Customer Said Bouaziz", itemId: customers[0].id, newValue: "ACTIVE / RETAIL" },
      { userId: users[1].id, department: "orders", operation: "create", item: "Order ORD-1003", itemId: orderC.id, newValue: "NEW" },
      { userId: users[3].id, department: "payments", operation: "create", item: "Payment REC-01", previousValue: null, newValue: "10000 CASH" },
      { userId: admin.id, department: "pricing", operation: "edit", item: "Sunflower oil 5L retail", previousValue: "1490", newValue: "1450", motif: "Supplier price drop" },
    ],
  });

  void pf;
  void round;
}

main().finally(async () => prisma.$disconnect());
