// DSCM-X Node Manager Service
// Node registration and management (SEN, CEN, FXN, CTN)

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { v4 as uuidv4 } from 'uuid';


export interface NodeRegistrationRequest {
  nodeType: string; // SEN, CEN, FXN, CTN
  nodeName: string;
  sovereignBankId?: string;
  computeCapacity?: number;
  latency?: number;
  sovereignPriority?: number;
  riskWeight?: number;
}

export class DscmNodeManagerService {
  /**
   * Register compute node
   */
  async registerNode(request: NodeRegistrationRequest) {
    const nodeId = `DSCM-${request.nodeType}-${uuidv4()}`;

    return await prisma.dscmNode.create({
      data: {
        nodeId,
        sovereignBankId: request.sovereignBankId,
        nodeType: request.nodeType,
        nodeName: request.nodeName,
        computeCapacity: request.computeCapacity ? new Decimal(request.computeCapacity) : null,
        latency: request.latency || null,
        sovereignPriority: request.sovereignPriority || null,
        riskWeight: request.riskWeight ? new Decimal(request.riskWeight) : null,
        status: 'active',
        registeredAt: new Date(),
        lastHeartbeat: new Date(),
      },
    });
  }

  /**
   * Update node heartbeat
   */
  async updateHeartbeat(nodeId: string) {
    return await prisma.dscmNode.update({
      where: { nodeId },
      data: {
        lastHeartbeat: new Date(),
      },
    });
  }

  /**
   * Get node by ID
   */
  async getNode(nodeId: string) {
    return await prisma.dscmNode.findUnique({
      where: { nodeId },
    });
  }

  /**
   * Get nodes by type
   */
  async getNodesByType(nodeType: string) {
    return await prisma.dscmNode.findMany({
      where: {
        nodeType,
        status: 'active',
      },
    });
  }

  /**
   * Get nodes for sovereign bank
   */
  async getNodesForBank(sovereignBankId: string) {
    return await prisma.dscmNode.findMany({
      where: {
        sovereignBankId,
        status: 'active',
      },
    });
  }

  /**
   * Update node status
   */
  async updateNodeStatus(nodeId: string, status: string) {
    return await prisma.dscmNode.update({
      where: { nodeId },
      data: { status },
    });
  }
}

export const dscmNodeManagerService = new DscmNodeManagerService();

