import { db, NasRouter, LivePppSession, IpPool } from '../../database/db';
import { NetworkDriverFactory } from '../network/driver.factory';

export class NasService {
  /**
   * Returns list of configured NAS BRAS routers with real-time health
   */
  public static getRouters(): NasRouter[] {
    return db.nas_routers.map(r => {
      // Simulate live CPU fluctuation
      const cpu = Math.min(Math.max(r.cpu_load + Math.floor(Math.random() * 5 - 2), 5), 90);
      return {
        ...r,
        cpu_load: cpu,
        active_sessions_count: db.live_ppp_sessions.filter(s => s.routerId === r.id).length || r.active_sessions_count
      };
    });
  }

  /**
   * Returns live PPP sessions across routers
   */
  public static getLiveSessions(): LivePppSession[] {
    return db.live_ppp_sessions.map(s => {
      // Simulate live traffic fluctuation
      const rx = Math.floor(s.rxRateKbps * (0.9 + Math.random() * 0.2));
      const tx = Math.floor(s.txRateKbps * (0.9 + Math.random() * 0.2));
      return {
        ...s,
        rxRateKbps: rx,
        txRateKbps: tx
      };
    });
  }

  /**
   * Disconnect an active PPP session
   */
  public static async disconnectSession(username: string) {
    db.live_ppp_sessions = db.live_ppp_sessions.filter(s => s.username !== username);
    const sub = db.subscribers.find(s => s.username === username);
    if (sub) {
      await NetworkDriverFactory.executeAction('terminateLiveSession', {
        id: sub.id,
        username: sub.username,
        driver_type: sub.driver_type,
        status: sub.status
      });
    }
    db.persist();
    return { success: true, message: `Session for '${username}' terminated from NAS.` };
  }

  /**
   * Returns IP address pools
   */
  public static getIpPools(): IpPool[] {
    return db.ip_pools;
  }
}
