import { PrismaClient } from "@prisma/client";
import { hash } from "bcryptjs";

const prisma = new PrismaClient();

// ==================== HELPERS ====================

function randomInt(min: number, max: number): number {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomFloat(min: number, max: number, decimals = 2): number {
  return parseFloat((Math.random() * (max - min) + min).toFixed(decimals));
}

function randomDate(daysAgoMax: number, daysAgoMin = 0): Date {
  const now = new Date();
  const daysAgo = randomInt(daysAgoMin, daysAgoMax);
  now.setDate(now.getDate() - daysAgo);
  now.setHours(randomInt(0, 23), randomInt(0, 59), randomInt(0, 59));
  return now;
}

function futureDate(daysFromNow: number): Date {
  const d = new Date();
  d.setDate(d.getDate() + daysFromNow);
  return d;
}

function pickRandom<T>(arr: T[]): T {
  return arr[randomInt(0, arr.length - 1)];
}

// Hash password once
let hashedPassword: string | null = null;
async function getPassword(): Promise<string> {
  if (!hashedPassword) {
    hashedPassword = await hash("password123", 10);
  }
  return hashedPassword;
}

function generateInvoiceNumber(monthOffset: number, seq: number): string {
  const d = new Date();
  d.setMonth(d.getMonth() - monthOffset);
  const m = d.getMonth() + 1;
  const y = d.getFullYear();
  return `INV-${y}${String(m).padStart(2, "0")}-${String(seq).padStart(4, "0")}`;
}

// ==================== DATA ====================

const AREAS = [
  { name: "Dhanmondi", code: "DHM", description: "Dhanmondi Residential Area" },
  { name: "Gulshan", code: "GUL", description: "Gulshan Commercial & Residential" },
  { name: "Banani", code: "BAN", description: "Banani Residential Area" },
  { name: "Mirpur", code: "MIR", description: "Mirpur DOHS & Residential" },
  { name: "Uttara", code: "UTT", description: "Uttara Model Town" },
  { name: "Mohammadpur", code: "MOH", description: "Mohammadpur Residential Area" },
  { name: "Tejgaon", code: "TEJ", description: "Tejgaon Industrial Area" },
  { name: "Bashundhara", code: "BAS", description: "Bashundhara R/A" },
];

const PLANS = [
  { name: "Basic 5Mbps", description: "Entry-level broadband for light browsing", speedDown: 5, speedUp: 2, price: 10, duration: 30 },
  { name: "Home 10Mbps", description: "Perfect for streaming and video calls", speedDown: 10, speedUp: 5, price: 15, duration: 30 },
  { name: "Home 20Mbps", description: "Great for families with moderate usage", speedDown: 20, speedUp: 10, price: 25, duration: 30 },
  { name: "Home 50Mbps", description: "High-speed home connection for heavy users", speedDown: 50, speedUp: 25, price: 45, duration: 30 },
  { name: "Business 30Mbps", description: "Business-grade connectivity with SLA", speedDown: 30, speedUp: 15, price: 55, duration: 30 },
  { name: "Business 50Mbps", description: "Enhanced business connectivity", speedDown: 50, speedUp: 25, price: 80, duration: 30 },
  { name: "Business 100Mbps", description: "Premium business fiber connection", speedDown: 100, speedUp: 50, price: 150, duration: 30 },
  { name: "Enterprise 100Mbps", description: "Enterprise-grade fiber with dedicated support", speedDown: 100, speedUp: 100, price: 200, duration: 30 },
  { name: "Enterprise 200Mbps", description: "High-capacity enterprise connection", speedDown: 200, speedUp: 200, price: 350, duration: 30 },
  { name: "Enterprise 500Mbps", description: "Ultra-fast enterprise backbone connection", speedDown: 500, speedUp: 500, price: 600, duration: 30 },
  { name: "Home 100Mbps", description: "Ultra-fast home fiber connection", speedDown: 100, speedUp: 50, price: 85, duration: 30 },
  { name: "Basic 10Mbps", description: "Affordable 10Mbps for students", speedDown: 10, speedUp: 5, price: 12, duration: 30 },
];

const STAFF_USERS = [
  { name: "Rafiq Ahmed", email: "rafiq@netbd.com", phone: "01711000001", username: "rafiq.admin", role: "SUPER_ADMIN", status: "ACTIVE", areaIndex: 0, connectionType: "FIBER" },
  { name: "Fatima Begum", email: "fatima@netbd.com", phone: "01711000002", username: "fatima.admin", role: "SUPER_ADMIN", status: "ACTIVE", areaIndex: 0, connectionType: "FIBER" },
  { name: "Kamal Hossain", email: "kamal@netbd.com", phone: "01812000003", username: "kamal.admin", role: "ADMIN", status: "ACTIVE", areaIndex: 0, connectionType: "FIBER" },
  { name: "Nusrat Jahan", email: "nusrat@netbd.com", phone: "01812000004", username: "nusrat.admin", role: "ADMIN", status: "ACTIVE", areaIndex: 1, connectionType: "FIBER" },
  { name: "Tanvir Islam", email: "tanvir@netbd.com", phone: "01913000005", username: "tanvir.admin", role: "ADMIN", status: "ACTIVE", areaIndex: 2, connectionType: "FIBER" },
  { name: "Arif Rahman", email: "arif@netbd.com", phone: "01614000006", username: "arif.op", role: "OPERATOR", status: "ACTIVE", areaIndex: 3, connectionType: "FIBER" },
  { name: "Sadia Afrin", email: "sadia@netbd.com", phone: "01614000007", username: "sadia.op", role: "OPERATOR", status: "ACTIVE", areaIndex: 4, connectionType: "FIBER" },
  { name: "Mehedi Hasan", email: "mehedi@netbd.com", phone: "01515000008", username: "mehedi.op", role: "OPERATOR", status: "ACTIVE", areaIndex: 5, connectionType: "FIBER" },
  { name: "Rima Akter", email: "rima@netbd.com", phone: "01515000009", username: "rima.op", role: "OPERATOR", status: "ACTIVE", areaIndex: 6, connectionType: "FIBER" },
  { name: "Shakil Uddin", email: "shakil@netbd.com", phone: "01416000010", username: "shakil.op", role: "OPERATOR", status: "SUSPENDED", areaIndex: 7, connectionType: "FIBER" },
];

const RESELLER_USERS = [
  { name: "Habibur Rahman", email: "habib.reseller@gmail.com", phone: "01722000011", username: "habib.reseller", areaIndex: 0, commissionType: "PERCENTAGE", commissionValue: 10, walletBalance: 5000, totalEarned: 12500 },
  { name: "Jamil Ahmed", email: "jamil.reseller@gmail.com", phone: "01822000012", username: "jamil.reseller", areaIndex: 1, commissionType: "PERCENTAGE", commissionValue: 12, walletBalance: 3200, totalEarned: 8700 },
  { name: "Momena Khatun", email: "momena.reseller@gmail.com", phone: "01932000013", username: "momena.reseller", areaIndex: 3, commissionType: "FIXED", commissionValue: 5, walletBalance: 1500, totalEarned: 4200 },
  { name: "Sohel Rana", email: "sohel.reseller@gmail.com", phone: "01632000014", username: "sohel.reseller", areaIndex: 4, commissionType: "PERCENTAGE", commissionValue: 8, walletBalance: 2800, totalEarned: 7600 },
  { name: "Taslima Akhter", email: "taslima.reseller@gmail.com", phone: "01542000015", username: "taslima.reseller", areaIndex: 6, commissionType: "PERCENTAGE", commissionValue: 15, walletBalance: 4100, totalEarned: 9800 },
];

const CLIENT_USERS = [
  { name: "Md. Rahim Uddin", email: "rahimuddin@gmail.com", phone: "01715010001", areaIndex: 0, planIndex: 1, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 0 },
  { name: "Salma Khatun", email: "salmakhatun@gmail.com", phone: "01715010002", areaIndex: 0, planIndex: 2, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 0 },
  { name: "Enamul Haque", email: "enamul.haque@gmail.com", phone: "01815010003", areaIndex: 0, planIndex: 0, status: "EXPIRED", connectionType: "WIRELESS", resellerIndex: -1 },
  { name: "Nasreen Begum", email: "nasreen.begum@gmail.com", phone: "01815010004", areaIndex: 1, planIndex: 3, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 1 },
  { name: "Khalid bin Walid", email: "khalid.walid@gmail.com", phone: "01915010005", areaIndex: 1, planIndex: 7, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 1 },
  { name: "Shamima Akter", email: "shamima.akter@gmail.com", phone: "01615010006", areaIndex: 1, planIndex: 4, status: "SUSPENDED", connectionType: "ETHERNET", resellerIndex: -1 },
  { name: "Abdul Karim", email: "abdul.karim@gmail.com", phone: "01515010007", areaIndex: 2, planIndex: 2, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Farzana Mim", email: "farzana.mim@gmail.com", phone: "01415010008", areaIndex: 2, planIndex: 5, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Jahangir Alam", email: "jahangir.alam@gmail.com", phone: "01725010009", areaIndex: 2, planIndex: 1, status: "EXPIRED", connectionType: "WIRELESS", resellerIndex: -1 },
  { name: "Asma Begum", email: "asma.begum@gmail.com", phone: "01725010010", areaIndex: 3, planIndex: 0, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 2 },
  { name: "Imran Hossain", email: "imran.hossain@gmail.com", phone: "01825010011", areaIndex: 3, planIndex: 2, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 2 },
  { name: "Rehana Parvin", email: "rehana.parvin@gmail.com", phone: "01925010012", areaIndex: 3, planIndex: 1, status: "PENDING", connectionType: "WIRELESS", resellerIndex: -1 },
  { name: "Mohammad Ali", email: "mohammad.ali@gmail.com", phone: "01625010013", areaIndex: 3, planIndex: 3, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 2 },
  { name: "Ayesha Siddika", email: "ayesha.siddika@gmail.com", phone: "01525010014", areaIndex: 4, planIndex: 6, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 3 },
  { name: "Razzak Sheikh", email: "razzak.sheikh@gmail.com", phone: "01425010015", areaIndex: 4, planIndex: 8, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 3 },
  { name: "Morium Begum", email: "morium.begum@gmail.com", phone: "01735010016", areaIndex: 4, planIndex: 0, status: "EXPIRED", connectionType: "WIRELESS", resellerIndex: -1 },
  { name: "Safiqul Islam", email: "safiqul.islam@gmail.com", phone: "01735010017", areaIndex: 4, planIndex: 2, status: "ACTIVE", connectionType: "ETHERNET", resellerIndex: 3 },
  { name: "Shirin Akter", email: "shirin.akter@gmail.com", phone: "01835010018", areaIndex: 4, planIndex: 1, status: "SUSPENDED", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Golam Mostofa", email: "golam.mostofa@gmail.com", phone: "01935010019", areaIndex: 5, planIndex: 3, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Khaleda Zia", email: "khaleda.zia@gmail.com", phone: "01635010020", areaIndex: 5, planIndex: 0, status: "ACTIVE", connectionType: "WIRELESS", resellerIndex: -1 },
  { name: "Zahid Hasan", email: "zahid.hasan@gmail.com", phone: "01535010021", areaIndex: 5, planIndex: 2, status: "CLOSED", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Nargis Akter", email: "nargis.akter@gmail.com", phone: "01435010022", areaIndex: 5, planIndex: 1, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Shafiq Ahmed", email: "shafiq.ahmed@gmail.com", phone: "01745010023", areaIndex: 6, planIndex: 4, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 4 },
  { name: "Rokeya Begum", email: "rokeya.begum@gmail.com", phone: "01745010024", areaIndex: 6, planIndex: 5, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 4 },
  { name: "Rezwan Khan", email: "rezwan.khan@gmail.com", phone: "01845010025", areaIndex: 6, planIndex: 7, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 4 },
  { name: "Firoz Alam", email: "firoz.alam@gmail.com", phone: "01945010026", areaIndex: 6, planIndex: 1, status: "EXPIRED", connectionType: "WIRELESS", resellerIndex: -1 },
  { name: "Tasnuva Rahman", email: "tasnuva.rahman@gmail.com", phone: "01645010027", areaIndex: 7, planIndex: 3, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Monir Hossain", email: "monir.hossain@gmail.com", phone: "01545010028", areaIndex: 7, planIndex: 9, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Sumaiya Islam", email: "sumaiya.islam@gmail.com", phone: "01445010029", areaIndex: 7, planIndex: 2, status: "PENDING", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Nizam Uddin", email: "nizam.uddin@gmail.com", phone: "01755010030", areaIndex: 0, planIndex: 4, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 0 },
  { name: "Halima Khatun", email: "halima.khatun@gmail.com", phone: "01755010031", areaIndex: 0, planIndex: 6, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Badrul Alam", email: "badrul.alam@gmail.com", phone: "01855010032", areaIndex: 1, planIndex: 8, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Rashida Akter", email: "rashida.akter@gmail.com", phone: "01955010033", areaIndex: 1, planIndex: 3, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 1 },
  { name: "Yunus Miah", email: "yunus.miah@gmail.com", phone: "01655010034", areaIndex: 2, planIndex: 0, status: "ACTIVE", connectionType: "WIRELESS", resellerIndex: -1 },
  { name: "Kulsum Begum", email: "kulsum.begum@gmail.com", phone: "01555010035", areaIndex: 3, planIndex: 1, status: "EXPIRED", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Fazlul Haque", email: "fazlul.haque@gmail.com", phone: "01455010036", areaIndex: 4, planIndex: 4, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 3 },
  { name: "Sharmin Sultana", email: "sharmin.sultana@gmail.com", phone: "01765010037", areaIndex: 5, planIndex: 2, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Abdul Quddus", email: "abdul.quddus@gmail.com", phone: "01765010038", areaIndex: 6, planIndex: 3, status: "SUSPENDED", connectionType: "ETHERNET", resellerIndex: -1 },
  { name: "Nilufar Yasmin", email: "nilufar.yasmin@gmail.com", phone: "01865010039", areaIndex: 7, planIndex: 5, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Masud Parvez", email: "masud.parvez@gmail.com", phone: "01965010040", areaIndex: 0, planIndex: 10, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 0 },
  { name: "Jannatul Ferdous", email: "jannatul.ferdous@gmail.com", phone: "01665010041", areaIndex: 2, planIndex: 11, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Wasim Akram", email: "wasim.akram@gmail.com", phone: "01565010042", areaIndex: 4, planIndex: 6, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Sabrina Chowdhury", email: "sabrina.chowdhury@gmail.com", phone: "01465010043", areaIndex: 6, planIndex: 7, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 4 },
  { name: "Iqbal Hossain", email: "iqbal.hossain@gmail.com", phone: "01775010044", areaIndex: 1, planIndex: 9, status: "ACTIVE", connectionType: "FIBER", resellerIndex: 1 },
  { name: "Papiya Akter", email: "papiya.akter@gmail.com", phone: "01775010045", areaIndex: 3, planIndex: 0, status: "PENDING", connectionType: "WIRELESS", resellerIndex: -1 },
  { name: "Delwar Hossain", email: "delwar.hossain@gmail.com", phone: "01875010046", areaIndex: 5, planIndex: 3, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Nasima Begum", email: "nasima.begum2@gmail.com", phone: "01975010047", areaIndex: 7, planIndex: 2, status: "EXPIRED", connectionType: "FIBER", resellerIndex: -1 },
  { name: "Ripon Kumar", email: "ripon.kumar@gmail.com", phone: "01675010048", areaIndex: 0, planIndex: 1, status: "ACTIVE", connectionType: "FIBER", resellerIndex: -1 },
];

const SYSTEM_SETTINGS = [
  { key: "company_name", value: "NetBD ISP Solutions", type: "STRING" },
  { key: "company_address", value: "45/A, Gulshan Avenue, Dhaka 1212, Bangladesh", type: "STRING" },
  { key: "company_phone", value: "+880-2-8888-0001", type: "STRING" },
  { key: "company_email", value: "info@netbd.com", type: "STRING" },
  { key: "currency", value: "BDT", type: "STRING" },
  { key: "currency_symbol", value: "৳", type: "STRING" },
  { key: "tax_rate", value: "5", type: "NUMBER" },
  { key: "late_fee_percentage", value: "2", type: "NUMBER" },
  { key: "invoice_due_days", value: "15", type: "NUMBER" },
  { key: "auto_suspend_days", value: "30", type: "NUMBER" },
  { key: "whatsapp_enabled", value: "true", type: "BOOLEAN" },
  { key: "sms_enabled", value: "false", type: "BOOLEAN" },
  { key: "maintenance_mode", value: "false", type: "BOOLEAN" },
];

const TICKET_SUBJECTS = [
  { subject: "Internet connection is very slow", description: "My internet speed has been extremely slow for the past 3 days. I am getting only 1-2 Mbps instead of my plan's 10 Mbps. Please look into this urgently.", priority: "HIGH", status: "IN_PROGRESS" },
  { subject: "No internet access since yesterday", description: "I have had no internet connectivity since yesterday evening. The ONT light is blinking red. I have tried restarting the router but nothing changed.", priority: "URGENT", status: "OPEN" },
  { subject: "Billing discrepancy in last invoice", description: "I was charged $45 for the last month but my plan is $25 (Home 20Mbps). Please correct the invoice amount.", priority: "MEDIUM", status: "OPEN" },
  { subject: "Request for plan upgrade", description: "I would like to upgrade from Home 10Mbps to Home 50Mbps plan. Please let me know the process and any additional charges.", priority: "LOW", status: "OPEN" },
  { subject: "Intermittent connection drops", description: "My connection drops every 10-15 minutes and reconnects automatically. This is affecting my work from home schedule. Started happening 2 days ago.", priority: "HIGH", status: "IN_PROGRESS" },
  { subject: "Router configuration help needed", description: "I just got a new router and need help configuring it for the fiber connection. My PPPoE credentials are not working.", priority: "MEDIUM", status: "OPEN" },
  { subject: "Payment confirmation not received", description: "I paid my bill via bKash 2 days ago but the invoice still shows as unpaid. Transaction ID: TXN897654. Please update.", priority: "MEDIUM", status: "RESOLVED" },
  { subject: "Request for connection relocation", description: "I am moving to a new address in Gulshan next month. Can you relocate my connection there? What are the charges for relocation?", priority: "LOW", status: "OPEN" },
  { subject: "High latency during gaming", description: "I am experiencing very high ping (200ms+) during online gaming sessions, especially in the evening. Can you optimize routing for game servers?", priority: "MEDIUM", status: "OPEN" },
  { subject: "ONT device showing faulty", description: "My ONT device keeps restarting randomly and the PON light keeps blinking. I suspect the hardware is faulty and needs replacement.", priority: "HIGH", status: "IN_PROGRESS" },
  { subject: "Need static IP for CCTV", description: "I want to set up remote monitoring for my CCTV system and need a static IP address. Is this possible with my current plan?", priority: "LOW", status: "RESOLVED" },
  { subject: "Speed test shows incorrect results", description: "Speed tests consistently show lower speeds than my subscribed plan. Getting 8Mbps on a 20Mbps plan. Already tried different speed test servers.", priority: "MEDIUM", status: "OPEN" },
  { subject: "Account access issue", description: "I am unable to login to the customer portal. It says my account is locked. Please help me regain access to my account.", priority: "HIGH", status: "RESOLVED" },
  { subject: "WiFi coverage is very weak", description: "The WiFi signal from the provided router barely reaches my bedroom. Can you provide a WiFi extender or replace the router with a better one?", priority: "MEDIUM", status: "OPEN" },
  { subject: "Request for temporary connection suspension", description: "I will be traveling abroad for 2 months. Can I temporarily suspend my connection and resume it when I return? Will I be charged during suspension?", priority: "LOW", status: "CLOSED" },
  { subject: "Frequent DNS resolution failures", description: "Many websites fail to load with DNS errors. I have to refresh multiple times. Using Google DNS as a workaround currently. Please fix the default DNS.", priority: "HIGH", status: "OPEN" },
  { subject: "Duplicate invoice generated", description: "I received two invoices for the same billing period (November). Invoice numbers INV-202411-0045 and INV-202411-0089. Please cancel the duplicate.", priority: "MEDIUM", status: "RESOLVED" },
  { subject: "VPN connection issues", description: "I cannot connect to my corporate VPN through the ISP connection. It was working fine until last week. Other VPNs also seem blocked.", priority: "HIGH", status: "IN_PROGRESS" },
  { subject: "New connection application", description: "I want to apply for a new fiber connection at my residence in Uttara, Sector 7. Please guide me through the process and timeline.", priority: "MEDIUM", status: "OPEN" },
  { subject: "Router keeps overheating", description: "The provided router becomes very hot to touch after a few hours of use and then the connection drops. I think it needs replacement due to overheating.", priority: "HIGH", status: "OPEN" },
  { subject: "Feedback: Great service!", description: "Just wanted to say thank you for the excellent service. The connection has been rock solid and speeds are consistent. Keep up the good work!", priority: "LOW", status: "CLOSED" },
  { subject: "Need bill in different name", description: "The bill is generated under my previous name. I have recently changed my name legally. How can I update the billing name?", priority: "LOW", status: "OPEN" },
];

const TICKET_REPLIES = [
  "We are looking into this issue. A technician has been assigned and will visit your location within 24 hours.",
  "Thank you for your patience. The issue has been identified as a fiber cut in your area. Repair work is underway.",
  "We have verified your payment. The invoice status has been updated to PAID. Sorry for the inconvenience.",
  "Your plan upgrade request has been processed. The new plan will be effective from your next billing cycle.",
  "Our team is currently working on resolving this. We will update you with progress within 4 hours.",
  "The router configuration guide has been sent to your email. Please follow the steps carefully. Let us know if you need further assistance.",
  "We have replaced your ONT device. The new device has been provisioned and activated. Please check your connection now.",
  "Your static IP has been configured. The IP address is 103.xx.xx.xx. You can now use it for your CCTV remote access.",
  "This issue has been resolved from our end. The DNS servers have been updated. Please restart your router and try again.",
  "Your connection relocation request has been noted. A survey team will visit your new address next week to assess feasibility.",
];

const ACTIVITY_ACTIONS = [
  { action: "USER_LOGIN", module: "AUTH", details: "User logged in successfully" },
  { action: "USER_LOGOUT", module: "AUTH", details: "User logged out" },
  { action: "CREATE_INVOICE", module: "BILLING", details: "Generated monthly invoice for subscription" },
  { action: "PAYMENT_RECEIVED", module: "BILLING", details: "Payment received via bKash" },
  { action: "PAYMENT_RECEIVED", module: "BILLING", details: "Payment received via Nagad" },
  { action: "PAYMENT_RECEIVED", module: "BILLING", details: "Cash payment collected" },
  { action: "PLAN_CHANGE", module: "SUBSCRIPTION", details: "Upgraded plan from Home 10Mbps to Home 50Mbps" },
  { action: "ACTIVATE_USER", module: "USER", details: "New user activated and connection provisioned" },
  { action: "SUSPEND_USER", module: "USER", details: "User suspended due to non-payment" },
  { action: "REACTIVATE_USER", module: "USER", details: "User reactivated after payment confirmation" },
  { action: "CREATE_TICKET", module: "SUPPORT", details: "Support ticket created" },
  { action: "CLOSE_TICKET", module: "SUPPORT", details: "Support ticket closed as resolved" },
  { action: "OLT_REBOOT", module: "NETWORK", details: "OLT device rebooted for maintenance" },
  { action: "ONU_PROVISION", module: "NETWORK", details: "New ONU provisioned and linked to user" },
  { action: "RESELLER_COMMISSION", module: "RESELLER", details: "Commission credited to reseller wallet" },
  { action: "SYSTEM_BACKUP", module: "SYSTEM", details: "Automated database backup completed" },
  { action: "SETTINGS_UPDATE", module: "SYSTEM", details: "System settings updated" },
  { action: "EXPORT_DATA", module: "REPORTS", details: "Monthly revenue report exported" },
  { action: "USER_CREATED", module: "USER", details: "New user account created by admin" },
  { action: "PASSWORD_RESET", module: "AUTH", details: "Password reset initiated by user" },
];

const WHATSAPP_MESSAGES = [
  { message: "Your NetBD invoice INV-202411-0023 of ৳1,575 is due on Dec 15, 2024. Please pay on time to avoid late fees.", template: "invoice_reminder" },
  { message: "Payment of ৳1,575 received for invoice INV-202411-0023. Thank you for choosing NetBD!", template: "payment_confirmation" },
  { message: "Your internet subscription will expire on Dec 20, 2024. Renew now to avoid service interruption.", template: "expiry_reminder" },
  { message: "Welcome to NetBD! Your fiber connection has been activated. Plan: Home 20Mbps. Enjoy blazing fast internet!", template: "welcome" },
  { message: "Scheduled maintenance notice: There will be a brief downtime on Dec 25, 2024 from 2:00 AM to 4:00 AM for network upgrades.", template: "maintenance_notice" },
  { message: "Your NetBD invoice INV-202410-0156 of ৳2,362 has been overdue for 15 days. A late fee of ৳47 has been applied. Please pay immediately.", template: "overdue_notice" },
  { message: "Your support ticket #TK-0042 has been resolved. If you're satisfied with the resolution, no further action is needed.", template: "ticket_resolved" },
  { message: "Great news! Your plan has been upgraded from Home 10Mbps to Home 50Mbps. The new plan is effective immediately.", template: "plan_upgrade" },
  { message: "Your connection has been suspended due to non-payment. Please clear your dues to reactivate. Call 8888-0001 for assistance.", template: "suspension_notice" },
  { message: "Happy New Year from NetBD! We appreciate your continued trust. Use code NET2025 for 5% discount on annual plans.", template: "promotional" },
  { message: "Your ticket #TK-0051 is being handled by our technician. ETA for resolution: Today, 6:00 PM.", template: "ticket_update" },
  { message: "Reminder: Your monthly bill of ৳787 is due tomorrow. Pay via bKash/Nagad or visit our office.", template: "payment_reminder" },
];

const OLT_DEVICES = [
  { name: "OLT-DHM-01", ipAddress: "192.168.1.1", username: "admin", password: "admin123", model: "Huawei MA5608T", firmware: "MA5608T V800R019", portCount: 16, status: "ONLINE" },
  { name: "OLT-GUL-01", ipAddress: "192.168.1.2", username: "admin", password: "admin123", model: "ZTE C320", firmware: "C320 V4.0", portCount: 24, status: "ONLINE" },
  { name: "OLT-UTT-01", ipAddress: "192.168.1.3", username: "admin", password: "admin123", model: "Huawei MA5800-X15", firmware: "MA5800 V800R021", portCount: 32, status: "ONLINE" },
];

const CONNECTION_TYPES = ["FIBER", "WIRELESS", "ETHERNET"];
const PAYMENT_METHODS = ["CASH", "BKASH", "NAGAD", "BANK_TRANSFER", "SSLCOMMERZ"];
const TICKET_STATUSES = ["OPEN", "IN_PROGRESS", "RESOLVED", "CLOSED"];
const TICKET_PRIORITIES = ["LOW", "MEDIUM", "HIGH", "URGENT"];

// ==================== MAIN SEED FUNCTION ====================

async function main() {
  console.log("🌱 Starting seed...");

  // Clean up existing data
  console.log("🗑️ Cleaning existing data...");
  await prisma.payment.deleteMany();
  await prisma.commission.deleteMany();
  await prisma.resellerTransaction.deleteMany();
  await prisma.reseller.deleteMany();
  await prisma.ticketReply.deleteMany();
  await prisma.ticket.deleteMany();
  await prisma.invoice.deleteMany();
  await prisma.session.deleteMany();
  await prisma.subscription.deleteMany();
  await prisma.oNU.deleteMany();
  await prisma.oLTDevice.deleteMany();
  await prisma.activityLog.deleteMany();
  await prisma.whatsAppLog.deleteMany();
  await prisma.systemSetting.deleteMany();
  await prisma.user.deleteMany();
  await prisma.plan.deleteMany();
  await prisma.area.deleteMany();

  const password = await getPassword();

  // ==================== 1. SYSTEM SETTINGS ====================
  console.log("⚙️ Creating system settings...");
  const settings = await Promise.all(
    SYSTEM_SETTINGS.map((s) =>
      prisma.systemSetting.create({ data: s })
    )
  );
  console.log(`  ✅ Created ${settings.length} system settings`);

  // ==================== 2. AREAS ====================
  console.log("🗺️ Creating areas...");
  const areas = await Promise.all(
    AREAS.map((a) =>
      prisma.area.create({ data: a })
    )
  );
  console.log(`  ✅ Created ${areas.length} areas`);

  // ==================== 3. PLANS ====================
  console.log("📦 Creating plans...");
  const plans = await Promise.all(
    PLANS.map((p, i) =>
      prisma.plan.create({
        data: {
          ...p,
          areaId: null, // available in all areas
          isActive: true,
        },
      })
    )
  );
  console.log(`  ✅ Created ${plans.length} plans`);

  // ==================== 4. USERS ====================
  console.log("👥 Creating staff users...");
  const staffUsers = await Promise.all(
    STAFF_USERS.map((u) =>
      prisma.user.create({
        data: {
          email: u.email,
          password,
          name: u.name,
          phone: u.phone,
          username: u.username,
          role: u.role,
          status: u.status,
          address: `${AREAS[u.areaIndex].name}, Dhaka`,
          areaId: areas[u.areaIndex].id,
          connectionType: u.connectionType,
          createdAt: randomDate(180),
        },
      })
    )
  );
  console.log(`  ✅ Created ${staffUsers.length} staff users`);

  console.log("🏪 Creating reseller users...");
  const resellerUsers = await Promise.all(
    RESELLER_USERS.map((u) =>
      prisma.user.create({
        data: {
          email: u.email,
          password,
          name: u.name,
          phone: u.phone,
          username: u.username,
          role: "RESELLER",
          status: "ACTIVE",
          address: `${AREAS[u.areaIndex].name}, Dhaka`,
          areaId: areas[u.areaIndex].id,
          connectionType: "FIBER",
          createdAt: randomDate(180),
        },
      })
    )
  );
  console.log(`  ✅ Created ${resellerUsers.length} reseller users`);

  console.log("👤 Creating client users...");
  const clientUsers = await Promise.all(
    CLIENT_USERS.map((u) =>
      prisma.user.create({
        data: {
          email: u.email,
          password,
          name: u.name,
          phone: u.phone,
          username: u.email.split("@")[0],
          role: "CLIENT",
          status: u.status,
          address: `House ${randomInt(1, 150)}, Road ${randomInt(1, 30)}, ${AREAS[u.areaIndex].name}, Dhaka`,
          areaId: areas[u.areaIndex].id,
          connectionType: u.connectionType,
          resellerId: u.resellerIndex >= 0 ? resellerUsers[u.resellerIndex].id : null,
          ipAddress: `10.0.${u.areaIndex + 1}.${randomInt(2, 250)}`,
          macAddress: `AA:BB:CC:${randomHex()}:${randomHex()}:${randomHex()}`,
          createdAt: randomDate(180),
        },
      })
    )
  );
  console.log(`  ✅ Created ${clientUsers.length} client users`);

  // ==================== 5. RESELLERS ====================
  console.log("💰 Creating reseller profiles...");
  const resellers = await Promise.all(
    RESELLER_USERS.map((u, i) =>
      prisma.reseller.create({
        data: {
          userId: resellerUsers[i].id,
          commissionType: u.commissionType,
          commissionValue: u.commissionValue,
          walletBalance: u.walletBalance,
          totalEarned: u.totalEarned,
          isActive: true,
        },
      })
    )
  );
  console.log(`  ✅ Created ${resellers.length} reseller profiles`);

  // ==================== 6. SUBSCRIPTIONS ====================
  console.log("📋 Creating subscriptions...");
  const subscriptions: Array<{ id: string; userId: string; planId: string; status: string; expiryDate: Date }> = [];

  for (const cu of CLIENT_USERS) {
    const userIndex = CLIENT_USERS.indexOf(cu);
    const user = clientUsers[userIndex];
    const plan = plans[cu.planIndex];

    if (cu.status === "PENDING" || cu.status === "CLOSED") {
      // No active subscription for pending/closed
      continue;
    }

    const startDate = randomDate(150, 30);
    const isActive = cu.status === "ACTIVE";
    const expiryDate = isActive
      ? futureDate(randomInt(5, 25))
      : new Date(startDate.getTime() + plan.duration * 24 * 60 * 60 * 1000);

    const subscription = await prisma.subscription.create({
      data: {
        userId: user.id,
        planId: plan.id,
        startDate,
        expiryDate,
        status: isActive ? "ACTIVE" : "EXPIRED",
        autoRenew: isActive && Math.random() > 0.5,
      },
    });

    subscriptions.push({
      id: subscription.id,
      userId: user.id,
      planId: plan.id,
      status: subscription.status,
      expiryDate: subscription.expiryDate,
    });
  }
  console.log(`  ✅ Created ${subscriptions.length} subscriptions`);

  // ==================== 7. INVOICES ====================
  console.log("🧾 Creating invoices...");
  const invoices: Array<{ id: string; userId: string; subscriptionId: string; totalAmount: number; status: string; invoiceNumber: string; createdAt: Date }> = [];
  let invoiceSeq = 1;

  for (let monthOffset = 5; monthOffset >= 0; monthOffset--) {
    for (const sub of subscriptions) {
      const plan = plans.find((p) => p.id === sub.planId)!;
      const shouldHaveInvoice = Math.random() > 0.15; // 85% chance each month

      if (!shouldHaveInvoice) continue;

      const taxRate = 5;
      const discount = Math.random() > 0.85 ? randomFloat(2, 10) : 0;
      const lateFee = (monthOffset > 0 && Math.random() > 0.7) ? randomFloat(1, plan.price * 0.05) : 0;
      const amount = plan.price;
      const tax = parseFloat(((amount - discount) * taxRate / 100).toFixed(2));
      const totalAmount = parseFloat((amount - discount + tax + lateFee).toFixed(2));

      const isPaid = monthOffset < 4 && Math.random() > 0.25;
      const isDue = monthOffset >= 4 && Math.random() > 0.5;

      const invoiceDate = new Date();
      invoiceDate.setMonth(invoiceDate.getMonth() - monthOffset);
      invoiceDate.setDate(randomInt(1, 5));

      const dueDate = new Date(invoiceDate);
      dueDate.setDate(dueDate.getDate() + 15);

      const invoice = await prisma.invoice.create({
        data: {
          invoiceNumber: generateInvoiceNumber(monthOffset, invoiceSeq++),
          userId: sub.userId,
          subscriptionId: sub.id,
          amount,
          tax,
          discount,
          lateFee,
          totalAmount,
          dueDate,
          status: isPaid ? "PAID" : isDue ? "DUE" : "UNPAID",
          paidAmount: isPaid ? totalAmount : 0,
          notes: monthOffset === 0 ? "Current month invoice" : "",
          createdAt: invoiceDate,
        },
      });

      invoices.push({
        id: invoice.id,
        userId: sub.userId,
        subscriptionId: sub.id,
        totalAmount,
        status: invoice.status,
        invoiceNumber: invoice.invoiceNumber,
        createdAt: invoice.createdAt,
      });
    }
  }
  console.log(`  ✅ Created ${invoices.length} invoices`);

  // ==================== 8. PAYMENTS ====================
  console.log("💳 Creating payments...");
  const payments: Array<{ id: string; invoiceId: string; userId: string; amount: number }> = [];

  for (const inv of invoices) {
    if (inv.status !== "PAID") continue;

    const paymentDate = new Date(inv.createdAt);
    paymentDate.setDate(paymentDate.getDate() + randomInt(0, 10));

    const payment = await prisma.payment.create({
      data: {
        invoiceId: inv.id,
        userId: inv.userId,
        amount: inv.totalAmount,
        method: pickRandom(PAYMENT_METHODS),
        transactionId: `TXN${Date.now()}${randomInt(1000, 9999)}`,
        status: "PAID",
        notes: "",
        createdAt: paymentDate,
      },
    });

    payments.push({
      id: payment.id,
      invoiceId: inv.id,
      userId: inv.userId,
      amount: payment.amount,
    });
  }
  console.log(`  ✅ Created ${payments.length} payments`);

  // ==================== 9. SESSIONS ====================
  console.log("🌐 Creating sessions...");
  const sessions = [];

  // Active sessions for ACTIVE clients
  for (let i = 0; i < 15; i++) {
    const activeClient = clientUsers.filter((_, idx) => CLIENT_USERS[idx].status === "ACTIVE")[i];
    if (!activeClient) continue;

    const session = await prisma.session.create({
      data: {
        userId: activeClient.id,
        sessionId: `sess_${randomHex()}${randomHex()}${randomHex()}`,
        ipAddress: activeClient.ipAddress,
        macAddress: activeClient.macAddress,
        startTime: randomDate(2, 0),
        downloadBytes: randomFloat(0.5, 50) * 1073741824, // GB to bytes
        uploadBytes: randomFloat(0.1, 10) * 1073741824,
        duration: randomInt(3600, 86400),
        isActive: true,
        createdAt: randomDate(2, 0),
      },
    });
    sessions.push(session);
  }

  // Historical sessions
  for (let i = 0; i < 20; i++) {
    const client = pickRandom(clientUsers);
    const startTime = randomDate(60, 5);
    const duration = randomInt(600, 43200);

    const session = await prisma.session.create({
      data: {
        userId: client.id,
        sessionId: `sess_old_${randomHex()}${randomHex()}`,
        ipAddress: client.ipAddress || `10.0.${randomInt(1, 8)}.${randomInt(2, 250)}`,
        macAddress: client.macAddress,
        startTime,
        stopTime: new Date(startTime.getTime() + duration * 1000),
        downloadBytes: randomFloat(0.1, 20) * 1073741824,
        uploadBytes: randomFloat(0.05, 5) * 1073741824,
        duration,
        isActive: false,
        createdAt: startTime,
      },
    });
    sessions.push(session);
  }
  console.log(`  ✅ Created ${sessions.length} sessions`);

  // ==================== 10. TICKETS ====================
  console.log("🎫 Creating support tickets...");
  const tickets: Array<{ id: string; userId: string; status: string; priority: string }> = [];
  const allClientUsers = clientUsers.filter((_, idx) => 
    CLIENT_USERS[idx].status === "ACTIVE" || CLIENT_USERS[idx].status === "EXPIRED"
  );
  const allStaffUsers = staffUsers.filter(u => u.role === "ADMIN" || u.role === "OPERATOR" || u.role === "SUPER_ADMIN");

  for (let i = 0; i < TICKET_SUBJECTS.length; i++) {
    const ts = TICKET_SUBJECTS[i];
    const client = allClientUsers[i % allClientUsers.length];
    const assignedTo = allStaffUsers[randomInt(0, allStaffUsers.length - 1)];

    const ticket = await prisma.ticket.create({
      data: {
        userId: client.id,
        subject: ts.subject,
        description: ts.description,
        status: ts.status,
        priority: ts.priority,
        assignedTo: assignedTo.id,
        createdAt: randomDate(90, 5),
      },
    });

    tickets.push({
      id: ticket.id,
      userId: client.id,
      status: ts.status,
      priority: ts.priority,
    });
  }
  console.log(`  ✅ Created ${tickets.length} tickets`);

  // ==================== 11. TICKET REPLIES ====================
  console.log("💬 Creating ticket replies...");
  let replyCount = 0;

  for (let i = 0; i < tickets.length; i++) {
    const ticket = tickets[i];
    const numReplies = randomInt(1, 3);

    for (let j = 0; j < numReplies; j++) {
      const isAdmin = j === 0 || Math.random() > 0.4;
      const replyUser = isAdmin
        ? allStaffUsers[randomInt(0, allStaffUsers.length - 1)]
        : clientUsers.find((u) => u.id === ticket.userId) || clientUsers[0];

      await prisma.ticketReply.create({
        data: {
          ticketId: ticket.id,
          userId: replyUser.id,
          message: isAdmin
            ? TICKET_REPLIES[i % TICKET_REPLIES.length]
            : "Thank you for looking into this. Please let me know if you need any additional information from my side.",
          isAdmin,
          createdAt: new Date(Date.now() - (numReplies - j) * randomInt(3600000, 86400000)),
        },
      });
      replyCount++;
    }
  }
  console.log(`  ✅ Created ${replyCount} ticket replies`);

  // ==================== 12. COMMISSIONS ====================
  console.log("💵 Creating commissions...");
  const commissions: Array<{ id: string; resellerId: string; userId: string; invoiceId: string; amount: number }> = [];

  for (const pay of payments) {
    const user = clientUsers.find((u) => u.id === pay.userId);
    if (!user) continue;

    const clientData = CLIENT_USERS[clientUsers.indexOf(user)];
    if (!clientData || clientData.resellerIndex < 0) continue;

    const reseller = resellers[clientData.resellerIndex];
    const commissionAmount = reseller.commissionType === "PERCENTAGE"
      ? parseFloat((pay.amount * reseller.commissionValue / 100).toFixed(2))
      : reseller.commissionValue;

    const commission = await prisma.commission.create({
      data: {
        resellerId: reseller.id,
        userId: user.id,
        invoiceId: pay.invoiceId,
        amount: commissionAmount,
        type: "SUBSCRIPTION",
        status: Math.random() > 0.2 ? "PAID" : "PENDING",
        createdAt: new Date(),
      },
    });

    commissions.push({
      id: commission.id,
      resellerId: reseller.id,
      userId: user.id,
      invoiceId: pay.invoiceId,
      amount: commissionAmount,
    });
  }
  console.log(`  ✅ Created ${commissions.length} commissions`);

  // ==================== 13. RESELLER TRANSACTIONS ====================
  console.log("🔄 Creating reseller transactions...");
  let transactionCount = 0;

  for (const reseller of resellers) {
    const numTransactions = randomInt(3, 8);
    for (let i = 0; i < numTransactions; i++) {
      const type = pickRandom(["COMMISSION", "WITHDRAWAL", "COMMISSION", "COMMISSION", "ADJUSTMENT"]);
      const amount = type === "WITHDRAWAL"
        ? randomFloat(500, 3000)
        : type === "ADJUSTMENT"
          ? randomFloat(100, 500)
          : randomFloat(100, 2000);

      await prisma.resellerTransaction.create({
        data: {
          resellerId: reseller.id,
          amount: type === "WITHDRAWAL" ? -amount : amount,
          type,
          description: type === "COMMISSION"
            ? "Monthly subscription commission"
            : type === "WITHDRAWAL"
              ? "Wallet withdrawal request"
              : "Balance adjustment by admin",
          createdAt: randomDate(120),
        },
      });
      transactionCount++;
    }
  }
  console.log(`  ✅ Created ${transactionCount} reseller transactions`);

  // ==================== 14. OLT DEVICES ====================
  console.log("📡 Creating OLT devices...");
  const oltDevices = await Promise.all(
    OLT_DEVICES.map((o) =>
      prisma.oLTDevice.create({ data: o })
    )
  );
  console.log(`  ✅ Created ${oltDevices.length} OLT devices`);

  // ==================== 15. ONUs ====================
  console.log("🔌 Creating ONUs...");
  let onuCount = 0;
  const fiberClients = clientUsers.filter((_, idx) => 
    CLIENT_USERS[idx].connectionType === "FIBER" && 
    (CLIENT_USERS[idx].status === "ACTIVE" || CLIENT_USERS[idx].status === "EXPIRED")
  );

  for (let i = 0; i < Math.min(25, fiberClients.length); i++) {
    const client = fiberClients[i];
    const olt = oltDevices[i % oltDevices.length];
    const slot = randomInt(0, Math.floor(olt.portCount / 2));
    const port = randomInt(0, 15);
    const statuses = ["ONLINE", "ONLINE", "ONLINE", "ONLINE", "OFFLINE", "PROVISIONING", "FAULTY"];
    const onuStatus = CLIENT_USERS[clientUsers.indexOf(client)].status === "ACTIVE"
      ? pickRandom(statuses.slice(0, 4))
      : pickRandom(["OFFLINE", "OFFLINE", "PROVISIONING"]);

    await prisma.oNU.create({
      data: {
        oltId: olt.id,
        serialNumber: `HWTC${randomHex()}${randomHex()}${randomHex()}${randomHex()}`,
        slot,
        port,
        userId: client.id,
        status: onuStatus,
        signalStrength: onuStatus === "ONLINE" ? randomFloat(-25, -15) : 0,
        temperature: onuStatus === "ONLINE" ? randomFloat(35, 55) : 0,
        uptime: onuStatus === "ONLINE" ? randomInt(86400, 2592000) : 0,
        lastSeen: randomDate(3),
      },
    });
    onuCount++;
  }
  console.log(`  ✅ Created ${onuCount} ONUs`);

  // ==================== 16. ACTIVITY LOGS ====================
  console.log("📝 Creating activity logs...");
  let logCount = 0;

  for (let i = 0; i < 40; i++) {
    const action = ACTIVITY_ACTIONS[i % ACTIVITY_ACTIONS.length];
    const user = i < 15
      ? allStaffUsers[i % allStaffUsers.length]
      : clientUsers[i % clientUsers.length];

    await prisma.activityLog.create({
      data: {
        userId: user.id,
        action: action.action,
        module: action.module,
        details: action.details,
        ipAddress: `192.168.${randomInt(1, 10)}.${randomInt(1, 254)}`,
        createdAt: randomDate(120),
      },
    });
    logCount++;
  }
  console.log(`  ✅ Created ${logCount} activity logs`);

  // ==================== 17. WHATSAPP LOGS ====================
  console.log("📱 Creating WhatsApp logs...");
  const whatsappLogs = await Promise.all(
    WHATSAPP_MESSAGES.map((wm) =>
      prisma.whatsAppLog.create({
        data: {
          phoneNumber: `01${randomInt(7, 9)}${String(randomInt(10000000, 99999999))}`,
          message: wm.message,
          template: wm.template,
          status: pickRandom(["SENT", "DELIVERED", "DELIVERED", "PENDING", "FAILED"]),
          response: Math.random() > 0.7 ? "Message delivered successfully" : "",
          createdAt: randomDate(60),
        },
      })
    )
  );
  console.log(`  ✅ Created ${whatsappLogs.length} WhatsApp logs`);

  // ==================== SUMMARY ====================
  console.log("\n" + "=".repeat(60));
  console.log("📊 SEED SUMMARY");
  console.log("=".repeat(60));

  const counts = {
    SystemSettings: await prisma.systemSetting.count(),
    Areas: await prisma.area.count(),
    Plans: await prisma.plan.count(),
    Users: await prisma.user.count(),
    Subscriptions: await prisma.subscription.count(),
    Invoices: await prisma.invoice.count(),
    Payments: await prisma.payment.count(),
    Sessions: await prisma.session.count(),
    Tickets: await prisma.ticket.count(),
    TicketReplies: await prisma.ticketReply.count(),
    Resellers: await prisma.reseller.count(),
    Commissions: await prisma.commission.count(),
    ResellerTransactions: await prisma.resellerTransaction.count(),
    OLTDevices: await prisma.oLTDevice.count(),
    ONUs: await prisma.oNU.count(),
    ActivityLogs: await prisma.activityLog.count(),
    WhatsAppLogs: await prisma.whatsAppLog.count(),
  };

  for (const [name, count] of Object.entries(counts)) {
    console.log(`  ${name.padEnd(22)}: ${count}`);
  }

  const totalRecords = Object.values(counts).reduce((a, b) => a + b, 0);
  console.log("\n" + "-".repeat(60));
  console.log(`  Total Records: ${totalRecords}`);
  console.log("=".repeat(60));
  console.log("✅ Seed completed successfully!");
}

// ==================== HELPERS ====================

function randomHex(): string {
  return Math.floor(Math.random() * 256).toString(16).toUpperCase().padStart(2, "0");
}

// ==================== RUN ====================

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