// DBIS Hyper-Sovereign Monetary Nexus - Prime Nexus (HS0)
// Foundational DBIS monetary anchor

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


export interface PrimeNexusState {
  nexusId: string;
  layerNumber: number; // 0 for Prime Nexus
  anchorValue: number;
  stabilityIndex: number;
  connectedSovereigns: number;
}

export class HsmnNexusService {
  /**
   * Initialize or get Prime Nexus (HS0)
   */
  async getPrimeNexus(): Promise<PrimeNexusState | null> {
    const nexus = await prisma.hsmnNexusLayer.findFirst({
      where: {
        layerNumber: 0,
        status: 'active',
      },
      include: {
        sovereignMappings: {
          where: { status: 'active' },
        },
        realityStates: {
          where: { status: 'active' },
        },
      },
    });

    if (!nexus) {
      return null;
    }

    return {
      nexusId: nexus.nexusId,
      layerNumber: nexus.layerNumber,
      anchorValue: nexus.anchorValue?.toNumber() || 0,
      stabilityIndex: nexus.stabilityIndex?.toNumber() || 0,
      connectedSovereigns: nexus.sovereignMappings.length,
    };
  }

  /**
   * Create or update Prime Nexus
   */
  async initializePrimeNexus(anchorValue: number, stabilityIndex: number) {
    const nexusId = `HSMN-HS0-${uuidv4()}`;

    // Check if Prime Nexus exists
    const existing = await prisma.hsmnNexusLayer.findFirst({
      where: { layerNumber: 0, status: 'active' },
    });

    if (existing) {
      return await prisma.hsmnNexusLayer.update({
        where: { id: existing.id },
        data: {
          anchorValue,
          stabilityIndex,
          updatedAt: new Date(),
        },
      });
    }

    return await prisma.hsmnNexusLayer.create({
      data: {
        nexusId,
        layerNumber: 0,
        layerName: 'Prime Nexus',
        description: 'Foundational DBIS monetary anchor',
        anchorValue,
        stabilityIndex,
        status: 'active',
      },
    });
  }

  /**
   * Get nexus by layer number
   */
  async getNexusByLayer(layerNumber: number) {
    return await prisma.hsmnNexusLayer.findFirst({
      where: {
        layerNumber,
        status: 'active',
      },
      include: {
        sovereignMappings: true,
        realityStates: true,
      },
    });
  }

  /**
   * Get all active nexus layers
   */
  async getAllNexusLayers() {
    return await prisma.hsmnNexusLayer.findMany({
      where: { status: 'active' },
      orderBy: { layerNumber: 'asc' },
      include: {
        sovereignMappings: {
          where: { status: 'active' },
        },
      },
    });
  }
}

export const hsmnNexusService = new HsmnNexusService();

