// SNFN Node Service
// SFN, DFN, CSN node management

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


export interface CreateNodeRequest {
  nodeType: string; // sfn, dfn, csn
  nodeName: string;
  fundType: string; // sovereign_wealth_fund, supranational_institution, development_fund, stabilization_pool
  totalAssets?: string;
  availableLiquidity?: string;
}

export interface CreateDFNRequest {
  nodeId: string;
  directLendingCap: string;
  commodityBackedLoans?: boolean;
}

export interface CreateCSNRequest {
  nodeId: string;
  triggerCondition: string; // sri_critical, fx_collapse, commodity_shock
  triggerThreshold: string;
  stabilizationCap: string;
}

export interface NodeResult {
  nodeId: string;
  status: string;
}

export class SnfnNodeService {
  /**
   * Create supra fund node
   */
  async createNode(request: CreateNodeRequest): Promise<NodeResult> {
    const nodeId = `SNFN-${uuidv4()}`;

    const node = await prisma.supraFundNode.create({
      data: {
        nodeId,
        nodeType: request.nodeType,
        nodeName: request.nodeName,
        fundType: request.fundType,
        totalAssets: request.totalAssets ? new Decimal(request.totalAssets) : new Decimal(0),
        availableLiquidity: request.availableLiquidity
          ? new Decimal(request.availableLiquidity)
          : new Decimal(0),
        status: 'active',
      },
    });

    return {
      nodeId: node.nodeId,
      status: node.status,
    };
  }

  /**
   * Create development fund node
   */
  async createDFN(request: CreateDFNRequest): Promise<void> {
    await prisma.developmentFundNode.create({
      data: {
        dfnId: `SNFN-DFN-${uuidv4()}`,
        nodeId: request.nodeId,
        directLendingCap: new Decimal(request.directLendingCap),
        commodityBackedLoans: request.commodityBackedLoans ?? true,
        status: 'active',
      },
    });
  }

  /**
   * Create crisis stabilization node
   */
  async createCSN(request: CreateCSNRequest): Promise<void> {
    await prisma.crisisStabilizationNode.create({
      data: {
        csnId: `SNFN-CSN-${uuidv4()}`,
        nodeId: request.nodeId,
        triggerCondition: request.triggerCondition,
        triggerThreshold: new Decimal(request.triggerThreshold),
        stabilizationCap: new Decimal(request.stabilizationCap),
        status: 'standby',
      },
    });
  }

  /**
   * Activate CSN
   */
  async activateCSN(csnId: string): Promise<void> {
    await prisma.crisisStabilizationNode.update({
      where: { csnId },
      data: {
        status: 'activated',
        activatedAt: new Date(),
      },
    });
  }

  /**
   * Get node
   */
  async getNode(nodeId: string) {
    return await prisma.supraFundNode.findUnique({
      where: { nodeId },
      include: {
        loans: true,
        settlements: true,
      },
    });
  }

  /**
   * List nodes
   */
  async listNodes(nodeType?: string) {
    return await prisma.supraFundNode.findMany({
      where: nodeType ? { nodeType } : undefined,
      orderBy: { createdAt: 'desc' },
    });
  }
}

export const snfnNodeService = new SnfnNodeService();

