import fs from 'fs';
import path from 'path';

// ============================================================================
// ENTERPRISE ISP BILLING & OPERATIONS DATA MODELS (BSS/OSS COMPLETE STACK)
// ============================================================================

export interface Tenant {
  id: string;
  name: string;
  subdomain: string;
  logo_url: string;
  invoice_footer: string;
  vat_registration_no: string;
  status: 'active' | 'suspended';
  created_at: string;
}

export interface Reseller {
  id: string;
  tenant_id: string;
  name: string;
  email: string;
  phone: string;
  company_name: string;
  subdomain: string;
  logo_url: string;
  invoice_footer: string;
  status: 'active' | 'suspended';
  created_at: string;
}

export interface ResellerWallet {
  id: string;
  reseller_id: string;
  balance: number;
  currency: string;
  updated_at: string;
}

export interface ResellerLedgerEntry {
  id: string;
  reseller_id: string;
  type: 'TOPUP' | 'WHOLESALE_DEDUCTION' | 'REFUND' | 'MANUAL_ADJUSTMENT';
  amount: number;
  balance_before: number;
  balance_after: number;
  reference_id?: string;
  description: string;
  created_at: string;
}

export interface SystemSettings {
  mikrotik_host: string;
  mikrotik_port: number;
  mikrotik_user: string;
  mikrotik_pass: string;
  radius_host: string;
  radius_port: number;
  radius_db: string;
  radius_user: string;
  radius_pass: string;
  olt_ip: string;
  olt_port: number;
  olt_community: string;
  olt_brand: string;
  sms_provider: string;
  sms_api_key: string;
  sms_sender_id: string;
  bkash_app_key: string;
  bkash_app_secret: string;
  bkash_username: string;
  bkash_password: string;
  company_name: string;
  company_phone: string;
  company_address: string;
  vat_percentage: number;
}

export interface Package {
  id: string;
  tenant_id: string;
  name: string;
  speed_mbps: number;
  bdix_speed_mbps: number;
  youtube_speed_mbps: number;
  wholesale_price: number;
  default_retail_price: number;
  mikrotik_profile_name: string;
  radius_group_name: string;
  validity_days: number;
  fup_limit_gb?: number;
  fup_throttled_speed_mbps?: number;
  created_at: string;
}

export interface ResellerPackage {
  id: string;
  reseller_id: string;
  package_id: string;
  custom_retail_price: number;
  status: 'active' | 'inactive';
}

export interface NasRouter {
  id: string;
  tenant_id: string;
  name: string;
  model: string;
  ip_address: string;
  api_port: number;
  api_username: string;
  api_password_hash: string;
  radius_secret: string;
  coa_port: number;
  cpu_load: number;
  uptime_str: string;
  total_memory_mb: number;
  free_memory_mb: number;
  active_sessions_count: number;
  status: 'online' | 'offline';
  location: string;
}

export interface IpPool {
  id: string;
  router_id: string;
  name: string;
  pool_type: 'PPPOE_PRIVATE' | 'STATIC_PUBLIC' | 'HOTSPOT';
  range_start: string;
  range_end: string;
  total_ips: number;
  used_ips: number;
  gateway: string;
  dns_servers: string;
}

export interface LivePppSession {
  sessionId: string;
  username: string;
  routerId: string;
  routerName: string;
  ipAddress: string;
  macAddress: string;
  uptime: string;
  uptimeSeconds: number;
  rateLimit: string;
  bytesInMb: number;
  bytesOutMb: number;
  rxRateKbps: number;
  txRateKbps: number;
}

export interface Subscriber {
  id: string;
  tenant_id: string;
  reseller_id?: string;
  username: string;
  password_hash: string;
  full_name: string;
  phone: string;
  email?: string;
  national_id_or_passport?: string;
  address?: string;
  gps_lat?: number;
  gps_lng?: number;
  driver_type: 'MIKROTIK_API' | 'RADIUS';
  router_id?: string;
  package_id: string;
  ip_address?: string;
  mac_address?: string;
  connection_type: 'PPPOE' | 'STATIC_IP' | 'HOTSPOT';
  status: 'active' | 'expired' | 'suspended' | 'walled_garden' | 'grace_period';
  expiration_date: string; // ISO 8601
  grace_period_until?: string;
  fup_used_bytes: number;
  onu_id?: string;
  tj_box_id?: string;
  created_at: string;
  updated_at: string;
}

export interface Invoice {
  id: string;
  invoice_no: string;
  tenant_id: string;
  reseller_id?: string;
  subscriber_id: string;
  package_id: string;
  amount: number;
  vat_amount: number;
  discount_amount: number;
  net_amount: number;
  status: 'paid' | 'unpaid' | 'cancelled';
  due_date: string;
  paid_at?: string;
  payment_method?: string;
  created_at: string;
}

export interface Payment {
  id: string;
  invoice_id?: string;
  subscriber_id: string;
  reseller_id?: string;
  amount: number;
  gateway: 'BKASH_PAYBILL' | 'BKASH_SIM_SMS' | 'NAGAD' | 'ROCKET' | 'MANUAL_CASH' | 'COLLECTOR_CASH';
  trx_id: string;
  reference?: string;
  collector_name?: string;
  raw_payload?: string;
  status: 'completed' | 'failed' | 'reversed';
  created_at: string;
}

export interface OLT {
  id: string;
  tenant_id: string;
  name: string;
  brand: 'VSOL' | 'HUAWEI' | 'BDCOM' | 'ZTE';
  model: string;
  ip_address: string;
  snmp_port: number;
  snmp_community: string;
  ssh_user?: string;
  ssh_password?: string;
  status: 'online' | 'offline' | 'degraded';
  total_pon_ports: number;
  active_onus_total: number;
  location: string;
  created_at: string;
}

export interface PonPort {
  id: string;
  olt_id: string;
  port_number: number;
  port_name: string;
  max_onus: number;
  active_onus: number;
  optical_wavelength: string; // e.g. 1490nm Tx / 1310nm Rx
  status: 'online' | 'down';
}

export interface ONU {
  id: string;
  olt_id: string;
  pon_port_id: string;
  mac_serial: string;
  onu_type: 'EPON' | 'GPON' | 'XPON';
  subscriber_id?: string;
  rx_power_dbm: number;
  tx_power_dbm: number;
  temperature_celsius: number;
  voltage_volts: number;
  fiber_distance_meters: number;
  laser_status: 'healthy' | 'warning' | 'critical_fault';
  is_registered: boolean;
  discovered_at: string;
  last_scraped_at: string;
}

export interface TjBox {
  id: string;
  name: string;
  code: string;
  location_name: string;
  gps_lat: number;
  gps_lng: number;
  total_ports: number;
  used_ports: number;
  splitter_ratio: '1:8' | '1:16' | '1:32';
  olt_id: string;
  pon_port_id: string;
}

export interface SupportTicket {
  id: string;
  ticket_no: string;
  tenant_id: string;
  reseller_id?: string;
  subscriber_id: string;
  title: string;
  category: 'Slow Internet' | 'Red Light on Router / LOS' | 'Billing Issue' | 'Hardware Replacement' | 'WiFi Issue' | 'General';
  severity: 'low' | 'medium' | 'high' | 'critical';
  status: 'open' | 'in_progress' | 'resolved' | 'closed';
  description: string;
  assigned_to?: string;
  resolution_notes?: string;
  created_at: string;
  updated_at: string;
}

export interface ExpenseRecord {
  id: string;
  tenant_id: string;
  category: 'UPSTREAM_IIG_NTTN' | 'POP_ELECTRICITY' | 'POP_RENT' | 'STAFF_SALARY' | 'FIBER_MAINTENANCE' | 'OFFICE_MISC';
  title: string;
  amount: number;
  paid_to: string;
  payment_method: string;
  expense_date: string;
  created_at: string;
}

export interface SmsLog {
  id: string;
  phone: string;
  subscriber_username?: string;
  template_type: 'EXPIRY_REMINDER' | 'WELCOME' | 'PAYMENT_CONFIRM' | 'FIBER_FAULT_ALERT' | 'PROMO_BULK';
  message: string;
  gateway: 'GREENWEB' | 'BULKSMS_BD' | 'ANDROID_SIM_MODEM' | 'TWILIO';
  status: 'sent' | 'delivered' | 'failed';
  cost_bdt: number;
  created_at: string;
}

export interface RadCheck {
  id: number;
  username: string;
  attribute: string;
  op: string;
  value: string;
}

export interface RadReply {
  id: number;
  username: string;
  attribute: string;
  op: string;
  value: string;
}

export interface RadAcct {
  radacctid: number;
  acctsessionid: string;
  username: string;
  nasipaddress: string;
  framedipaddress: string;
  acctstarttime: string;
  acctstoptime?: string;
  acctsessiontime?: number;
  acctinputoctets?: number;
  acctoutputoctets?: number;
  acctterminatecause?: string;
}

export interface AuditLog {
  id: string;
  tenant_id?: string;
  actor_type: 'SYSTEM' | 'SUPER_ADMIN' | 'RESELLER' | 'SUBSCRIBER' | 'WORKER' | 'BKASH_GATEWAY' | 'FIELD_TECH';
  actor_id?: string;
  action: string;
  metadata?: Record<string, any>;
  created_at: string;
}

// ============================================================================
// DATABASE MANAGER WITH TRANSACTION LOCKING
// ============================================================================

class EnterpriseDatabaseManager {
  private dataDir: string;
  private dbFilePath: string;
  private locks: Map<string, Promise<void>> = new Map();

  public tenants: Tenant[] = [];
  public resellers: Reseller[] = [];
  public reseller_wallets: ResellerWallet[] = [];
  public reseller_ledger: ResellerLedgerEntry[] = [];
  public packages: Package[] = [];
  public reseller_packages: ResellerPackage[] = [];
  public nas_routers: NasRouter[] = [];
  public ip_pools: IpPool[] = [];
  public live_ppp_sessions: LivePppSession[] = [];
  public subscribers: Subscriber[] = [];
  public invoices: Invoice[] = [];
  public payments: Payment[] = [];
  public olts: OLT[] = [];
  public pon_ports: PonPort[] = [];
  public onus: ONU[] = [];
  public tj_boxes: TjBox[] = [];
  public support_tickets: SupportTicket[] = [];
  public expense_records: ExpenseRecord[] = [];
  public sms_logs: SmsLog[] = [];
  public radcheck: RadCheck[] = [];
  public radreply: RadReply[] = [];
  public radacct: RadAcct[] = [];
  public audit_logs: AuditLog[] = [];
  public settings!: SystemSettings;

  constructor() {
    this.dataDir = path.join(process.cwd(), 'data');
    this.dbFilePath = path.join(this.dataDir, 'isp_database.json');
    this.initialize();
  }

  private initialize() {
    if (!fs.existsSync(this.dataDir)) {
      fs.mkdirSync(this.dataDir, { recursive: true });
    }

    if (fs.existsSync(this.dbFilePath)) {
      try {
        const raw = fs.readFileSync(this.dbFilePath, 'utf8');
        const state = JSON.parse(raw);
        Object.assign(this, state);
        
        // Ensure new enterprise collections and settings exist
        if (!this.settings) {
          this.settings = {
            mikrotik_host: '192.168.88.1',
            mikrotik_port: 8728,
            mikrotik_user: 'admin',
            mikrotik_pass: '',
            radius_host: '127.0.0.1',
            radius_port: 5432,
            radius_db: 'radius',
            radius_user: 'postgres',
            radius_pass: 'root',
            olt_ip: '192.168.10.100',
            olt_port: 161,
            olt_community: 'public',
            olt_brand: 'VSOL',
            sms_provider: 'GREENWEB',
            sms_api_key: 'GW_LIVE_API_KEY',
            sms_sender_id: 'NEXGEN',
            bkash_app_key: 'bkash_app_key_demo',
            bkash_app_secret: 'bkash_app_secret_demo',
            bkash_username: '01712000000',
            bkash_password: 'bkash_password_demo',
            company_name: 'NexGen Gigabit Fiber Networks Ltd',
            company_phone: '09612-888999',
            company_address: 'Level 5, Gulshan-2, Dhaka-1212, Bangladesh',
            vat_percentage: 5.0
          };
          this.persist();
        }

        if (!this.nas_routers || this.nas_routers.length === 0) {
          this.seedInitialData();
          this.persist();
        }
      } catch (err) {
        console.warn('Resetting database state to comprehensive enterprise seed.');
        this.seedInitialData();
        this.persist();
      }
    } else {
      this.seedInitialData();
      this.persist();
    }
  }

  public persist() {
    try {
      const state = {
        tenants: this.tenants,
        resellers: this.resellers,
        reseller_wallets: this.reseller_wallets,
        reseller_ledger: this.reseller_ledger,
        packages: this.packages,
        reseller_packages: this.reseller_packages,
        nas_routers: this.nas_routers,
        ip_pools: this.ip_pools,
        live_ppp_sessions: this.live_ppp_sessions,
        subscribers: this.subscribers,
        invoices: this.invoices,
        payments: this.payments,
        olts: this.olts,
        pon_ports: this.pon_ports,
        onus: this.onus,
        tj_boxes: this.tj_boxes,
        support_tickets: this.support_tickets,
        expense_records: this.expense_records,
        sms_logs: this.sms_logs,
        radcheck: this.radcheck,
        radreply: this.radreply,
        radacct: this.radacct,
        audit_logs: this.audit_logs,
        settings: this.settings
      };
      fs.writeFileSync(this.dbFilePath, JSON.stringify(state, null, 2), 'utf8');
    } catch (e) {
      console.error('Failed to persist database:', e);
    }
  }

  /**
   * Row-Level Locking (SELECT ... FOR UPDATE) mechanism
   */
  public async withRowLock<T>(rowKey: string, action: () => Promise<T>): Promise<T> {
    while (this.locks.has(rowKey)) {
      await this.locks.get(rowKey);
    }

    let releaseLock: () => void = () => {};
    const lockPromise = new Promise<void>((resolve) => {
      releaseLock = resolve;
    });

    this.locks.set(rowKey, lockPromise);

    try {
      return await action();
    } finally {
      this.locks.delete(rowKey);
      releaseLock();
      this.persist();
    }
  }

  public logAudit(actorType: AuditLog['actor_type'], actorId: string, action: string, metadata?: Record<string, any>, tenantId?: string) {
    const entry: AuditLog = {
      id: `audit_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
      tenant_id: tenantId || 'tenant_main',
      actor_type: actorType,
      actor_id: actorId,
      action,
      metadata,
      created_at: new Date().toISOString()
    };
    this.audit_logs.unshift(entry);
    if (this.audit_logs.length > 500) this.audit_logs.pop();
    this.persist();
  }

  public seedInitialData() {
    const now = new Date();
    const futureDate30 = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString();
    const futureDate18 = new Date(now.getTime() + 18 * 24 * 60 * 60 * 1000).toISOString();
    const futureDate3 = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000).toISOString();
    const pastDate2Hours = new Date(now.getTime() - 2 * 60 * 60 * 1000).toISOString();

    this.tenants = [
      {
        id: 'tenant_main',
        name: 'NexGen Gigabit Fiber Networks Ltd',
        subdomain: 'nexgen',
        logo_url: '/src/assets/logo.png',
        invoice_footer: 'Thank you for choosing NexGen Gigabit Fiber. BTRC Licensed Nationwide ISP. 24/7 Support: 09612-888999',
        vat_registration_no: 'VAT-99882211-DHAKA',
        status: 'active',
        created_at: now.toISOString()
      }
    ];

    this.resellers = [
      {
        id: 'reseller_uttara',
        tenant_id: 'tenant_main',
        name: 'Tariqul Islam',
        email: 'tariqul@uttarafastnet.com',
        phone: '+8801711000001',
        company_name: 'Uttara FastNet (Sub-ISP)',
        subdomain: 'uttara-fastnet',
        logo_url: '/src/assets/reseller1.png',
        invoice_footer: 'Uttara FastNet Sub-ISP Hub, Sector 3, Uttara. 24/7 Hotline: 01711000001',
        status: 'active',
        created_at: now.toISOString()
      },
      {
        id: 'reseller_dhanmondi',
        tenant_id: 'tenant_main',
        name: 'Sayed Mahmud',
        email: 'info@dhanmondilink.com',
        phone: '+8801711000002',
        company_name: 'Dhanmondi Link Broadband',
        subdomain: 'dhanmondi-link',
        logo_url: '/src/assets/reseller2.png',
        invoice_footer: 'Dhanmondi Link Broadband, Road 27, Dhanmondi. 24/7 Hotline: 01711000002',
        status: 'active',
        created_at: now.toISOString()
      }
    ];

    this.reseller_wallets = [
      {
        id: 'wallet_uttara',
        reseller_id: 'reseller_uttara',
        balance: 15000.00,
        currency: 'BDT',
        updated_at: now.toISOString()
      },
      {
        id: 'wallet_dhanmondi',
        reseller_id: 'reseller_dhanmondi',
        balance: 8500.00,
        currency: 'BDT',
        updated_at: now.toISOString()
      }
    ];

    this.reseller_ledger = [
      {
        id: 'led_01',
        reseller_id: 'reseller_uttara',
        type: 'TOPUP',
        amount: 15000.00,
        balance_before: 0.00,
        balance_after: 15000.00,
        reference_id: 'BANK_DEP_9921',
        description: 'Initial Pre-Paid Wholesale Wallet Credit via Bank Wire',
        created_at: now.toISOString()
      },
      {
        id: 'led_02',
        reseller_id: 'reseller_dhanmondi',
        type: 'TOPUP',
        amount: 8500.00,
        balance_before: 0.00,
        balance_after: 8500.00,
        reference_id: 'BKASH_MERCHANT_771',
        description: 'Pre-Paid Wholesale Wallet Credit via bKash Merchant',
        created_at: now.toISOString()
      }
    ];

    // Enterprise Bandwidth Packages (with BDIX, YouTube Peering, and FUP)
    this.packages = [
      {
        id: 'pkg_starter_20m',
        tenant_id: 'tenant_main',
        name: 'Starter Fiber 20 Mbps',
        speed_mbps: 20,
        bdix_speed_mbps: 100,
        youtube_speed_mbps: 100,
        wholesale_price: 400.00,
        default_retail_price: 600.00,
        mikrotik_profile_name: 'prof_20mbps',
        radius_group_name: 'group_20mbps',
        validity_days: 30,
        fup_limit_gb: 1500,
        fup_throttled_speed_mbps: 10,
        created_at: now.toISOString()
      },
      {
        id: 'pkg_turbo_50m',
        tenant_id: 'tenant_main',
        name: 'Turbo Stream 50 Mbps',
        speed_mbps: 50,
        bdix_speed_mbps: 200,
        youtube_speed_mbps: 200,
        wholesale_price: 700.00,
        default_retail_price: 1000.00,
        mikrotik_profile_name: 'prof_50mbps',
        radius_group_name: 'group_50mbps',
        validity_days: 30,
        fup_limit_gb: 3000,
        fup_throttled_speed_mbps: 20,
        created_at: now.toISOString()
      },
      {
        id: 'pkg_gigabit_100m',
        tenant_id: 'tenant_main',
        name: 'Gigabit Ultra 100 Mbps',
        speed_mbps: 100,
        bdix_speed_mbps: 500,
        youtube_speed_mbps: 500,
        wholesale_price: 1200.00,
        default_retail_price: 1800.00,
        mikrotik_profile_name: 'prof_100mbps',
        radius_group_name: 'group_100mbps',
        validity_days: 30,
        fup_limit_gb: 5000,
        fup_throttled_speed_mbps: 50,
        created_at: now.toISOString()
      }
    ];

    this.reseller_packages = [
      {
        id: 'rp_01',
        reseller_id: 'reseller_uttara',
        package_id: 'pkg_starter_20m',
        custom_retail_price: 650.00,
        status: 'active'
      },
      {
        id: 'rp_02',
        reseller_id: 'reseller_uttara',
        package_id: 'pkg_turbo_50m',
        custom_retail_price: 1050.00,
        status: 'active'
      },
      {
        id: 'rp_03',
        reseller_id: 'reseller_dhanmondi',
        package_id: 'pkg_starter_20m',
        custom_retail_price: 600.00,
        status: 'active'
      }
    ];

    // NAS BRAS Routers (MikroTik Cloud Core / CCR2004 / CHR)
    this.nas_routers = [
      {
        id: 'router_core_01',
        tenant_id: 'tenant_main',
        name: 'MikroTik CCR2004-16G-2S+ Core BRAS',
        model: 'CCR2004-16G-2S+',
        ip_address: '192.168.88.1',
        api_port: 8728,
        api_username: 'api_billing',
        api_password_hash: 'secure_router_pass',
        radius_secret: 'radius_shared_secret_2026',
        coa_port: 3799,
        cpu_load: 14,
        uptime_str: '48d 12h 34m',
        total_memory_mb: 4096,
        free_memory_mb: 3412,
        active_sessions_count: 842,
        status: 'online',
        location: 'Central NOC Datacenter (Dhaka)'
      },
      {
        id: 'router_pop_uttara',
        tenant_id: 'tenant_main',
        name: 'MikroTik CCR1009-7G-1C-1S+ (Uttara POP)',
        model: 'CCR1009-7G',
        ip_address: '10.10.0.1',
        api_port: 8728,
        api_username: 'api_billing',
        api_password_hash: 'secure_router_pass',
        radius_secret: 'radius_shared_secret_2026',
        coa_port: 3799,
        cpu_load: 22,
        uptime_str: '21d 08h 15m',
        total_memory_mb: 2048,
        free_memory_mb: 1540,
        active_sessions_count: 320,
        status: 'online',
        location: 'Uttara Sector 3 Sub-POP'
      }
    ];

    // IP Address Pools (Public & CGNAT Private)
    this.ip_pools = [
      {
        id: 'pool_cgnat_01',
        router_id: 'router_core_01',
        name: 'CGNAT-PPPoE-Pool-01',
        pool_type: 'PPPOE_PRIVATE',
        range_start: '10.10.20.2',
        range_end: '10.10.23.254',
        total_ips: 1020,
        used_ips: 618,
        gateway: '10.10.20.1',
        dns_servers: '8.8.8.8, 1.1.1.1'
      },
      {
        id: 'pool_public_01',
        router_id: 'router_core_01',
        name: 'Static-Public-Corporate-Pool',
        pool_type: 'STATIC_PUBLIC',
        range_start: '103.140.22.10',
        range_end: '103.140.22.250',
        total_ips: 240,
        used_ips: 184,
        gateway: '103.140.22.1',
        dns_servers: '8.8.8.8, 1.1.1.1'
      }
    ];

    // Active Live PPP Sessions (Real-Time Ingestion)
    this.live_ppp_sessions = [
      {
        sessionId: 'sess_9981',
        username: 'tanvir.ahmed',
        routerId: 'router_core_01',
        routerName: 'MikroTik CCR2004',
        ipAddress: '10.10.20.15',
        macAddress: '00:1A:2B:3C:4D:5E',
        uptime: '2d 14h 22m',
        uptimeSeconds: 224520,
        rateLimit: '50M/50M',
        bytesInMb: 14280.4,
        bytesOutMb: 58920.8,
        rxRateKbps: 4280,
        txRateKbps: 34100
      },
      {
        sessionId: 'sess_9982',
        username: 'rahim.khan',
        routerId: 'router_core_01',
        routerName: 'MikroTik CCR2004',
        ipAddress: '10.10.20.16',
        macAddress: '00:1A:2B:3C:4D:5F',
        uptime: '5h 18m',
        uptimeSeconds: 19080,
        rateLimit: '20M/20M',
        bytesInMb: 3200.1,
        bytesOutMb: 14100.2,
        rxRateKbps: 1200,
        txRateKbps: 18500
      }
    ];

    // Physical OLT Nodes (VSOL, Huawei, BDCOM, ZTE)
    this.olts = [
      {
        id: 'olt_vsol_01',
        tenant_id: 'tenant_main',
        name: 'VSOL V1600G1-B GPON Central',
        brand: 'VSOL',
        model: 'V1600G1-B',
        ip_address: '192.168.100.10',
        snmp_port: 161,
        snmp_community: 'nexgen-snmp',
        ssh_user: 'admin',
        ssh_password: 'vsol_password',
        status: 'online',
        total_pon_ports: 8,
        active_onus_total: 123,
        location: 'Central NOC Rack 04',
        created_at: now.toISOString()
      },
      {
        id: 'olt_huawei_02',
        tenant_id: 'tenant_main',
        name: 'Huawei SmartAX MA5608T',
        brand: 'HUAWEI',
        model: 'MA5608T (GPFD)',
        ip_address: '192.168.100.20',
        snmp_port: 161,
        snmp_community: 'nexgen-huawei',
        ssh_user: 'root',
        ssh_password: 'huawei_password',
        status: 'online',
        total_pon_ports: 16,
        active_onus_total: 240,
        location: 'Uttara Hub POP Rack 02',
        created_at: now.toISOString()
      },
      {
        id: 'olt_bdcom_03',
        tenant_id: 'tenant_main',
        name: 'BDCOM GP3600-08 GPON',
        brand: 'BDCOM',
        model: 'GP3600-08',
        ip_address: '192.168.100.30',
        snmp_port: 161,
        snmp_community: 'public',
        status: 'online',
        total_pon_ports: 8,
        active_onus_total: 88,
        location: 'Dhanmondi POP',
        created_at: now.toISOString()
      },
      {
        id: 'olt_zte_04',
        tenant_id: 'tenant_main',
        name: 'ZTE ZXA10 C320 OLT',
        brand: 'ZTE',
        model: 'C320 GPON/EPON',
        ip_address: '192.168.100.40',
        snmp_port: 161,
        snmp_community: 'public',
        status: 'online',
        total_pon_ports: 16,
        active_onus_total: 195,
        location: 'Mirpur POP',
        created_at: now.toISOString()
      }
    ];

    this.pon_ports = [
      { id: 'pon_1', olt_id: 'olt_vsol_01', port_number: 1, port_name: 'PON 1 (Sector 3 North)', max_onus: 64, active_onus: 28, optical_wavelength: '1490nm / 1310nm', status: 'online' },
      { id: 'pon_2', olt_id: 'olt_vsol_01', port_number: 2, port_name: 'PON 2 (Sector 3 South)', max_onus: 64, active_onus: 34, optical_wavelength: '1490nm / 1310nm', status: 'online' },
      { id: 'pon_3', olt_id: 'olt_vsol_01', port_number: 3, port_name: 'PON 3 (Sector 7 East)', max_onus: 64, active_onus: 19, optical_wavelength: '1490nm / 1310nm', status: 'online' },
      { id: 'pon_4', olt_id: 'olt_vsol_01', port_number: 4, port_name: 'PON 4 (Sector 7 West)', max_onus: 64, active_onus: 42, optical_wavelength: '1490nm / 1310nm', status: 'online' },
      { id: 'pon_5', olt_id: 'olt_huawei_02', port_number: 1, port_name: 'PON 1 (Dhanmondi 27)', max_onus: 128, active_onus: 86, optical_wavelength: '1490nm / 1310nm', status: 'online' },
      { id: 'pon_6', olt_id: 'olt_huawei_02', port_number: 2, port_name: 'PON 2 (Dhanmondi 32)', max_onus: 128, active_onus: 75, optical_wavelength: '1490nm / 1310nm', status: 'online' }
    ];

    // Fiber TJ Box / Splitter Nodes (Distribution Map)
    this.tj_boxes = [
      {
        id: 'tj_box_01',
        name: 'TJ Box #14 (Road 7, Sector 3)',
        code: 'TJ-UTT-07',
        location_name: 'Pole #42, Sector 3, Uttara',
        gps_lat: 23.8682,
        gps_lng: 90.3984,
        total_ports: 16,
        used_ports: 12,
        splitter_ratio: '1:16',
        olt_id: 'olt_vsol_01',
        pon_port_id: 'pon_1'
      },
      {
        id: 'tj_box_02',
        name: 'TJ Box #08 (Road 14, Sector 7)',
        code: 'TJ-UTT-14',
        location_name: 'Pole #19, Sector 7, Uttara',
        gps_lat: 23.8745,
        gps_lng: 90.3921,
        total_ports: 8,
        used_ports: 7,
        splitter_ratio: '1:8',
        olt_id: 'olt_vsol_01',
        pon_port_id: 'pon_2'
      }
    ];

    // ONUs with Telemetry
    this.onus = [
      {
        id: 'onu_01_healthy',
        olt_id: 'olt_vsol_01',
        pon_port_id: 'pon_1',
        mac_serial: 'VSOL-48A1092F',
        onu_type: 'XPON',
        subscriber_id: 'sub_tanvir',
        rx_power_dbm: -18.4,
        tx_power_dbm: 2.1,
        temperature_celsius: 42.5,
        voltage_volts: 3.28,
        fiber_distance_meters: 840,
        laser_status: 'healthy',
        is_registered: true,
        discovered_at: now.toISOString(),
        last_scraped_at: now.toISOString()
      },
      {
        id: 'onu_02_warning',
        olt_id: 'olt_vsol_01',
        pon_port_id: 'pon_2',
        mac_serial: 'VSOL-99B231C1',
        onu_type: 'XPON',
        subscriber_id: 'sub_rahim',
        rx_power_dbm: -25.2,
        tx_power_dbm: 1.8,
        temperature_celsius: 44.1,
        voltage_volts: 3.25,
        fiber_distance_meters: 1650,
        laser_status: 'warning',
        is_registered: true,
        discovered_at: now.toISOString(),
        last_scraped_at: now.toISOString()
      },
      {
        id: 'onu_03_critical',
        olt_id: 'olt_vsol_01',
        pon_port_id: 'pon_2',
        mac_serial: 'HWTC-55A38411',
        onu_type: 'GPON',
        subscriber_id: 'sub_shamim',
        rx_power_dbm: -29.8,
        tx_power_dbm: 0.2,
        temperature_celsius: 47.8,
        voltage_volts: 3.10,
        fiber_distance_meters: 2100,
        laser_status: 'critical_fault',
        is_registered: true,
        discovered_at: now.toISOString(),
        last_scraped_at: now.toISOString()
      },
      {
        id: 'onu_04_unregistered',
        olt_id: 'olt_vsol_01',
        pon_port_id: 'pon_3',
        mac_serial: 'HWTC-78F9A120',
        onu_type: 'GPON',
        subscriber_id: undefined,
        rx_power_dbm: -19.5,
        tx_power_dbm: 2.3,
        temperature_celsius: 39.2,
        voltage_volts: 3.30,
        fiber_distance_meters: 420,
        laser_status: 'healthy',
        is_registered: false,
        discovered_at: now.toISOString(),
        last_scraped_at: now.toISOString()
      }
    ];

    // Subscribers (with PPPoE, GPS Coordinates, Grace Period)
    this.subscribers = [
      {
        id: 'sub_tanvir',
        tenant_id: 'tenant_main',
        reseller_id: 'reseller_uttara',
        username: 'tanvir.ahmed',
        password_hash: 'pass_tanvir_123',
        full_name: 'Tanvir Ahmed',
        phone: '01812345678',
        email: 'tanvir@gmail.com',
        national_id_or_passport: 'NID-19928812349',
        address: 'House 42, Road 7, Sector 3, Uttara, Dhaka',
        gps_lat: 23.8684,
        gps_lng: 90.3982,
        driver_type: 'MIKROTIK_API',
        router_id: 'router_core_01',
        package_id: 'pkg_turbo_50m',
        ip_address: '10.10.20.15',
        mac_address: '00:1A:2B:3C:4D:5E',
        connection_type: 'PPPOE',
        status: 'active',
        expiration_date: futureDate18,
        fup_used_bytes: 429496729600, // 400 GB
        onu_id: 'onu_01_healthy',
        tj_box_id: 'tj_box_01',
        created_at: now.toISOString(),
        updated_at: now.toISOString()
      },
      {
        id: 'sub_rahim',
        tenant_id: 'tenant_main',
        reseller_id: 'reseller_uttara',
        username: 'rahim.khan',
        password_hash: 'pass_rahim_123',
        full_name: 'Rahim Khan',
        phone: '01912345678',
        email: 'rahim@gmail.com',
        national_id_or_passport: 'NID-19881122334',
        address: 'House 12, Road 3, Sector 3, Uttara, Dhaka',
        gps_lat: 23.8690,
        gps_lng: 90.3990,
        driver_type: 'RADIUS',
        router_id: 'router_core_01',
        package_id: 'pkg_starter_20m',
        ip_address: '10.10.20.16',
        mac_address: '00:1A:2B:3C:4D:5F',
        connection_type: 'PPPOE',
        status: 'active',
        expiration_date: futureDate3,
        fup_used_bytes: 214748364800, // 200 GB
        onu_id: 'onu_02_warning',
        tj_box_id: 'tj_box_01',
        created_at: now.toISOString(),
        updated_at: now.toISOString()
      },
      {
        id: 'sub_karim',
        tenant_id: 'tenant_main',
        reseller_id: 'reseller_dhanmondi',
        username: 'karim.hassan',
        password_hash: 'pass_karim_123',
        full_name: 'Karim Hassan',
        phone: '01712345678',
        email: 'karim@gmail.com',
        address: 'House 88, Road 27, Dhanmondi, Dhaka',
        gps_lat: 23.7461,
        gps_lng: 90.3742,
        driver_type: 'MIKROTIK_API',
        router_id: 'router_core_01',
        package_id: 'pkg_starter_20m',
        ip_address: '10.20.30.50',
        mac_address: '00:1A:2B:3C:4D:60',
        connection_type: 'PPPOE',
        status: 'expired',
        expiration_date: pastDate2Hours,
        fup_used_bytes: 322122547200,
        created_at: now.toISOString(),
        updated_at: now.toISOString()
      },
      {
        id: 'sub_shamim',
        tenant_id: 'tenant_main',
        reseller_id: 'reseller_uttara',
        username: 'shamim.reza',
        password_hash: 'pass_shamim_123',
        full_name: 'Shamim Reza',
        phone: '01612345678',
        email: 'shamim@gmail.com',
        address: 'House 19, Road 14, Sector 7, Uttara, Dhaka',
        gps_lat: 23.8748,
        gps_lng: 90.3925,
        driver_type: 'RADIUS',
        router_id: 'router_core_01',
        package_id: 'pkg_gigabit_100m',
        ip_address: '10.10.20.88',
        mac_address: '00:1A:2B:3C:4D:77',
        connection_type: 'STATIC_IP',
        status: 'suspended',
        expiration_date: futureDate30,
        fup_used_bytes: 858993459200,
        onu_id: 'onu_03_critical',
        tj_box_id: 'tj_box_02',
        created_at: now.toISOString(),
        updated_at: now.toISOString()
      }
    ];

    // Invoices
    this.invoices = [
      {
        id: 'inv_01',
        invoice_no: 'INV-2026-0801',
        tenant_id: 'tenant_main',
        reseller_id: 'reseller_uttara',
        subscriber_id: 'sub_tanvir',
        package_id: 'pkg_turbo_50m',
        amount: 1000.00,
        vat_amount: 50.00,
        discount_amount: 0.00,
        net_amount: 1050.00,
        status: 'paid',
        due_date: futureDate18,
        paid_at: now.toISOString(),
        payment_method: 'BKASH_PAYBILL',
        created_at: now.toISOString()
      },
      {
        id: 'inv_02',
        invoice_no: 'INV-2026-0802',
        tenant_id: 'tenant_main',
        reseller_id: 'reseller_uttara',
        subscriber_id: 'sub_rahim',
        package_id: 'pkg_starter_20m',
        amount: 619.05,
        vat_amount: 30.95,
        discount_amount: 0.00,
        net_amount: 650.00,
        status: 'unpaid',
        due_date: futureDate3,
        created_at: now.toISOString()
      }
    ];

    // Payments
    this.payments = [
      {
        id: 'pay_01',
        invoice_id: 'inv_01',
        subscriber_id: 'sub_tanvir',
        reseller_id: 'reseller_uttara',
        amount: 1050.00,
        gateway: 'BKASH_PAYBILL',
        trx_id: 'BK9A87X410',
        reference: 'tanvir.ahmed',
        status: 'completed',
        created_at: now.toISOString()
      }
    ];

    // Support Tickets
    this.support_tickets = [
      {
        id: 'tick_001',
        ticket_no: 'TCK-2026-091',
        tenant_id: 'tenant_main',
        reseller_id: 'reseller_uttara',
        subscriber_id: 'sub_shamim',
        title: 'Critical Optical Loss: Red Light on Router (LOS)',
        category: 'Red Light on Router / LOS',
        severity: 'critical',
        status: 'open',
        description: 'Automated Diagnostic Trigger: ONU HWTC-55A38411 registered RX power of -29.80 dBm exceeding -27.1 dBm threshold. Immediate line inspection required on Sector 7 distribution fiber.',
        assigned_to: 'Field Engineer Ashfaq',
        created_at: now.toISOString(),
        updated_at: now.toISOString()
      },
      {
        id: 'tick_002',
        ticket_no: 'TCK-2026-092',
        tenant_id: 'tenant_main',
        reseller_id: 'reseller_uttara',
        subscriber_id: 'sub_rahim',
        title: 'High Attenuation Warning on Sector 3',
        category: 'Slow Internet',
        severity: 'medium',
        status: 'in_progress',
        description: 'Subscriber reports buffering during video calls. Current optical reading is -25.2 dBm (Warning band). Fiber bend check recommended.',
        assigned_to: 'NOC Tech Farhan',
        created_at: now.toISOString(),
        updated_at: now.toISOString()
      }
    ];

    // ISP Accounts & Expense Ledger (Upstream Bandwidth, POP Bills, Salaries)
    this.expense_records = [
      {
        id: 'exp_01',
        tenant_id: 'tenant_main',
        category: 'UPSTREAM_IIG_NTTN',
        title: 'Summit Communications 10G IP Transit Bandwidth Buying',
        amount: 145000.00,
        paid_to: 'Summit Communications Ltd',
        payment_method: 'BANK_EFT',
        expense_date: now.toISOString().slice(0, 10),
        created_at: now.toISOString()
      },
      {
        id: 'exp_02',
        tenant_id: 'tenant_main',
        category: 'POP_ELECTRICITY',
        title: 'Uttara Sector 3 Sub-POP DESCO Electricity Bill',
        amount: 14200.00,
        paid_to: 'DESCO',
        payment_method: 'BKASH_PAYBILL',
        expense_date: now.toISOString().slice(0, 10),
        created_at: now.toISOString()
      },
      {
        id: 'exp_03',
        tenant_id: 'tenant_main',
        category: 'STAFF_SALARY',
        title: 'NOC Engineers & Line Technician Monthly Payroll',
        amount: 85000.00,
        paid_to: 'ISP Support Staff (4 Persons)',
        payment_method: 'BANK_TRANSFER',
        expense_date: now.toISOString().slice(0, 10),
        created_at: now.toISOString()
      }
    ];

    // SMS Notifications Log
    this.sms_logs = [
      {
        id: 'sms_01',
        phone: '01812345678',
        subscriber_username: 'tanvir.ahmed',
        template_type: 'PAYMENT_CONFIRM',
        message: 'Dear Tanvir Ahmed, your payment of Tk 1050.00 is received. TrxID: BK9A87X410. Internet renewed till 18-Sep-2026. NexGen Fiber.',
        gateway: 'GREENWEB',
        status: 'delivered',
        cost_bdt: 0.35,
        created_at: now.toISOString()
      },
      {
        id: 'sms_02',
        phone: '01912345678',
        subscriber_username: 'rahim.khan',
        template_type: 'EXPIRY_REMINDER',
        message: 'Dear Rahim Khan, your NexGen Fiber package expires in 3 days. Please pay Tk 650 via bKash Pay Bill to avoid disconnection.',
        gateway: 'GREENWEB',
        status: 'delivered',
        cost_bdt: 0.35,
        created_at: now.toISOString()
      }
    ];

    // FreeRADIUS Seeds
    this.radcheck = [
      { id: 1, username: 'rahim.khan', attribute: 'Cleartext-Password', op: ':=', value: 'pass_rahim_123' },
      { id: 2, username: 'shamim.reza', attribute: 'Cleartext-Password', op: ':=', value: 'pass_shamim_123' }
    ];

    this.radreply = [
      { id: 1, username: 'rahim.khan', attribute: 'Framed-IP-Address', op: ':=', value: '10.10.20.16' },
      { id: 2, username: 'rahim.khan', attribute: 'Mikrotik-Rate-Limit', op: ':=', value: '20M/20M' },
      { id: 3, username: 'shamim.reza', attribute: 'Framed-IP-Address', op: ':=', value: '10.10.20.88' },
      { id: 4, username: 'shamim.reza', attribute: 'Mikrotik-Rate-Limit', op: ':=', value: '100M/100M' }
    ];

    this.radacct = [
      {
        radacctid: 1,
        acctsessionid: 'sess_rad_88910',
        username: 'rahim.khan',
        nasipaddress: '192.168.10.1',
        framedipaddress: '10.10.20.16',
        acctstarttime: new Date(now.getTime() - 5 * 3600 * 1000).toISOString(),
        acctsessiontime: 18000,
        acctinputoctets: 429496729,
        acctoutputoctets: 1583920194
      }
    ];

    this.audit_logs = [
      {
        id: 'audit_init',
        tenant_id: 'tenant_main',
        actor_type: 'SYSTEM',
        actor_id: 'system_core',
        action: 'SYSTEM_BOOTSTRAP_INITIALIZED',
        metadata: { version: '2.0.0-ENTERPRISE', modules: 'BSS_OSS_COMPLETE' },
        created_at: now.toISOString()
      }
    ];
  }
}

export const db = new EnterpriseDatabaseManager();
