// 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.hsmn_nexus_layers.findFirst({
      where: {
        layerNumber: 0,
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      include: {
        hsmn_sovereign_mappings: {
          where: { status: 'active' },
        },
        hsmn_reality_states: {
          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.hsmn_sovereign_mappings.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.hsmn_nexus_layers.findFirst({
      where: { layerNumber: 0, status: 'active' },
    });

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

    return await prisma.hsmn_nexus_layers.create({
      data: {
        id: uuidv4(),
        nexusId,
        layerNumber: 0,
        layerName: 'Prime Nexus',
        description: 'Foundational DBIS monetary anchor',
        anchorValue,
        stabilityIndex,
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });
  }

  /**
   * Get nexus by layer number
   */
  async getNexusByLayer(layerNumber: number) {
    return await prisma.hsmn_nexus_layers.findFirst({
      where: {
        layerNumber,
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      include: {
        hsmn_sovereign_mappings: true,
        hsmn_reality_states: true,
      },
    });
  }

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

export const hsmnNexusService = new HsmnNexusService();

