// GSS Architecture Service
// Four-layer architecture: Sovereign, DBIS Master, Smart Clearing Fabric, Finality & Irreversibility

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


export interface SovereignSettlementNodeConfig {
  sovereignBankId: string;
  layer: string;
  nodeType: string;
}

export interface GssLayerConfig {
  layerNumber: number;
  layerName: string;
  description: string;
}

export class GssArchitectureService {
  /**
   * Create or initialize Sovereign Settlement Node (SSN) for a SCB
   * Layer 1: Sovereign Layer
   */
  async createSovereignSettlementNode(
    config: SovereignSettlementNodeConfig
  ): Promise<string> {
    const nodeId = `SSN-${config.sovereignBankId}-${uuidv4()}`;

    const node = await prisma.sovereignSettlementNode.create({
      data: {
        nodeId,
        sovereignBankId: config.sovereignBankId,
        layer: config.layer || 'layer_1_sovereign',
        nodeType: config.nodeType || 'SSN',
        status: 'active',
      },
    });

    return node.nodeId;
  }

  /**
   * Get SSN for a sovereign bank
   */
  async getSovereignSettlementNode(
    sovereignBankId: string
  ) {
    return await prisma.sovereignSettlementNode.findFirst({
      where: {
        sovereignBankId,
        status: 'active',
      },
    });
  }

  /**
   * Initialize GSS Layer
   * Layer 2: DBIS Master Settlement Layer
   * Layer 3: Smart Clearing Fabric (SCF)
   * Layer 4: Finality & Irreversibility Layer (FIL)
   */
  async initializeGssLayer(config: GssLayerConfig): Promise<string> {
    const layerId = `GSS-LAYER-${config.layerNumber}-${uuidv4()}`;

    const layer = await prisma.gssLayer.upsert({
      where: { layerId },
      update: {
        layerName: config.layerName,
        description: config.description,
        status: 'active',
      },
      create: {
        layerId,
        layerNumber: config.layerNumber,
        layerName: config.layerName,
        description: config.description,
        status: 'active',
      },
    });

    return layer.layerId;
  }

  /**
   * Get GSS layer by number
   */
  async getGssLayer(layerNumber: number) {
    return await prisma.gssLayer.findFirst({
      where: {
        layerNumber,
        status: 'active',
      },
    });
  }

  /**
   * Update SSN sync status
   */
  async updateSsnSyncStatus(nodeId: string): Promise<void> {
    await prisma.sovereignSettlementNode.update({
      where: { nodeId },
      data: {
        lastSyncAt: new Date(),
      },
    });
  }

  /**
   * Get all active SSNs
   */
  async getAllActiveSsn() {
    return await prisma.sovereignSettlementNode.findMany({
      where: {
        status: 'active',
      },
      include: {
        sovereignBank: true,
      },
    });
  }

  /**
   * Get layer status
   */
  async getLayerStatus(layerId: string) {
    const layer = await prisma.gssLayer.findUnique({
      where: { layerId },
    });

    if (!layer) {
      return null;
    }

    // Get SSNs for this layer
    const nodes = await prisma.sovereignSettlementNode.findMany({
      where: {
        layer: layer.layerName.toLowerCase().replace(/\s+/g, '_'),
        status: 'active',
      },
    });

    return {
      layer,
      activeNodes: nodes.length,
      totalNodes: nodes.length,
    };
  }
}

export const gssArchitectureService = new GssArchitectureService();

