// DSCN Node Manager
// DSCN node registration and management per SCB/private bank

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


export interface DscnNodeRegistrationRequest {
  sovereignBankId?: string;
  privateBankId?: string;
  nodeType: 'scb' | 'private_bank' | 'regulated_institution';
  nodeName: string;
  nodeAddress: string;
}

export class DscnNodeManagerService {
  /**
   * Register DSCN node
   */
  async registerNode(request: DscnNodeRegistrationRequest): Promise<{ nodeId: string }> {
    const nodeId = `DSCN-${uuidv4()}`;

    // Validate request
    if (request.nodeType === 'scb' && !request.sovereignBankId) {
      throw new Error('Sovereign bank ID required for SCB nodes');
    }

    if (request.nodeType === 'private_bank' && !request.privateBankId) {
      throw new Error('Private bank ID required for private bank nodes');
    }

    // Create node
    await prisma.dscnNode.create({
      data: {
        nodeId,
        sovereignBankId: request.sovereignBankId || null,
        privateBankId: request.privateBankId || null,
        nodeType: request.nodeType,
        nodeName: request.nodeName,
        nodeAddress: request.nodeAddress,
        registrationStatus: 'pending',
        status: 'active',
      },
    });

    logger.info('DSCN: Node registered', {
      nodeId,
      nodeType: request.nodeType,
      nodeName: request.nodeName,
    });

    return { nodeId };
  }

  /**
   * Approve node registration
   */
  async approveNode(nodeId: string): Promise<void> {
    await prisma.dscnNode.update({
      where: { nodeId },
      data: {
        registrationStatus: 'approved',
        approvedAt: new Date(),
        status: 'active',
      },
    });

    logger.info('DSCN: Node approved', { nodeId });
  }

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

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

export const dscnNodeManagerService = new DscnNodeManagerService();

