// PSG Relay Hubs Service
// SSR-Hub routing and latency optimization

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';


export interface RelayHubConfig {
  hubName: string;
  region: string;
  optimizedRoutes?: Record<string, unknown>[];
}

export class PsgRelayHubsService {
  /**
   * Create supra-sovereign relay hub
   */
  async createRelayHub(config: RelayHubConfig) {
    const grid = await prisma.psgMasterGrid.findFirst({
      where: { status: 'active' },
    });

    if (!grid) {
      throw new Error('Master grid not initialized');
    }

    const hubId = `SSR-HUB-${uuidv4()}`;

    return await prisma.supraSovereignRelayHub.create({
      data: {
        hubId,
        gridId: grid.gridId,
        hubName: config.hubName,
        region: config.region,
        optimizedRoutes: config.optimizedRoutes || [],
        latencyStats: {},
        status: 'active',
      },
    });
  }

  /**
   * Optimize routing path
   */
  async optimizeRoute(
    hubId: string,
    source: string,
    destination: string,
    routeConfig: Record<string, unknown>
  ) {
    const hub = await prisma.supraSovereignRelayHub.findUnique({
      where: { hubId },
    });

    if (!hub) {
      throw new Error(`Hub not found: ${hubId}`);
    }

    const optimizedRoutes = (hub.optimizedRoutes as Record<string, unknown>[]) || [];
    
    // Remove existing route if present
    const filteredRoutes = optimizedRoutes.filter(
      (r: any) => !(r.source === source && r.destination === destination)
    );

    filteredRoutes.push({
      source,
      destination,
      ...routeConfig,
      optimizedAt: new Date(),
    });

    return await prisma.supraSovereignRelayHub.update({
      where: { hubId },
      data: {
        optimizedRoutes: filteredRoutes,
      },
    });
  }

  /**
   * Update latency statistics
   */
  async updateLatencyStats(hubId: string, latency: number) {
    const hub = await prisma.supraSovereignRelayHub.findUnique({
      where: { hubId },
    });

    if (!hub) {
      throw new Error(`Hub not found: ${hubId}`);
    }

    const latencyStats = (hub.latencyStats as Record<string, unknown>) || {};
    const stats = latencyStats as Record<string, any>;

    if (!stats.average) {
      stats.average = latency;
      stats.min = latency;
      stats.max = latency;
      stats.count = 1;
    } else {
      stats.average = (stats.average * stats.count + latency) / (stats.count + 1);
      stats.min = Math.min(stats.min, latency);
      stats.max = Math.max(stats.max, latency);
      stats.count = stats.count + 1;
    }

    stats.lastUpdated = new Date();

    return await prisma.supraSovereignRelayHub.update({
      where: { hubId },
      data: {
        latencyStats: stats,
      },
    });
  }

  /**
   * Get hub by ID
   */
  async getHub(hubId: string) {
    return await prisma.supraSovereignRelayHub.findUnique({
      where: { hubId },
    });
  }

  /**
   * Get hubs by region
   */
  async getHubsByRegion(region: string) {
    return await prisma.supraSovereignRelayHub.findMany({
      where: {
        region,
        status: 'active',
      },
    });
  }

  /**
   * Get optimal route via hubs
   */
  async getOptimalRoute(source: string, destination: string) {
    const hubs = await prisma.supraSovereignRelayHub.findMany({
      where: {
        status: 'active',
      },
    });

    // Find route with lowest latency
    let bestRoute = null;
    let bestLatency = Infinity;

    for (const hub of hubs) {
      const routes = (hub.optimizedRoutes as Record<string, unknown>[]) || [];
      const route = routes.find(
        (r: any) => r.source === source && r.destination === destination
      );

      if (route && (route as any).latency < bestLatency) {
        bestLatency = (route as any).latency;
        bestRoute = {
          hubId: hub.hubId,
          hubName: hub.hubName,
          route,
        };
      }
    }

    return bestRoute;
  }
}

export const psgRelayHubsService = new PsgRelayHubsService();

