import { Injectable, Logger } from '@nestjs/common';
import os from 'os';
import ip from 'ip';

@Injectable()
export class NetworkService {
  private readonly logger = new Logger(NetworkService.name);

  /**
   * 获取网络适配器信息及网段
   */
  async getNetworkAdapters(): Promise<any> {
    try {
      this.logger.log('Getting network adapters');
      const interfaces = os.networkInterfaces();
      const networks: any[] = [];

      for (const [adapter, addrs] of Object.entries(interfaces)) {
        if (!addrs) continue;

        for (const addr of addrs) {
          if (addr.family === 'IPv4' && !addr.internal) {
            const ipAddress = addr.address;
            const subnetMask = addr.netmask;
            const cidr = ip.subnet(ipAddress, subnetMask);
            const networkCidr = `${cidr.networkAddress}/${cidr.subnetMaskLength}`;

            networks.push({
              adapter,
              network: networkCidr,
              ip: ipAddress,
              subnet_mask: subnetMask,
            });
          }
        }
      }

      return { networks };
    } catch (error) {
      this.logger.error('获取网络适配器信息失败', error);
      return { error: `获取网络适配器信息失败: ${error.message}` };
    }
  }
}
