// Multi-D-SEZ Bridge Service
// Bridge between multiple Digital Sovereign Economic Zones
// Supplement B: MetaverseDubai Integration Framework

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '@/infrastructure/monitoring/logger';
import { crossMetaverseFxService } from './cross-metaverse-fx.service';
import { Decimal } from '@prisma/client/runtime/library';


export interface MultiDsezBridgeRequest {
  sourceDsezId: string;
  targetDsezId: string;
  assetId: string;
  amount: string;
  currencyCode: string;
  conversionMethod?: 'ssu' | 'qmu' | 'hmu' | 'direct';
}

export interface MultiDsezBridgeResult {
  bridgeId: string;
  status: string;
  fxTransactionId?: string;
}

export class MultiDsezBridgeService {
  /**
   * Create bridge between multiple D-SEZs
   * Enables asset transfer and FX between different metaverse economic zones
   */
  async createMultiDsezBridge(
    request: MultiDsezBridgeRequest
  ): Promise<MultiDsezBridgeResult> {
    logger.info('Multi-D-SEZ Bridge: Creating bridge', { request });

    // Step 1: Get source and target D-SEZs
    const sourceDsez = await prisma.digitalSovereignEconomicZone.findUnique({
      where: { dsezId: request.sourceDsezId },
      include: { node: true },
    });

    const targetDsez = await prisma.digitalSovereignEconomicZone.findUnique({
      where: { dsezId: request.targetDsezId },
      include: { node: true },
    });

    if (!sourceDsez || !targetDsez) {
      throw new Error('Source or target D-SEZ not found');
    }

    // Step 2: Verify liquidity flow is enabled for both D-SEZs
    if (!sourceDsez.liquidityFlowEnabled || !targetDsez.liquidityFlowEnabled) {
      throw new Error('Liquidity flow not enabled for one or both D-SEZs');
    }

    // Step 3: Execute cross-metaverse FX if needed
    let fxTransactionId: string | undefined;
    if (sourceDsez.node.metaverseName !== targetDsez.node.metaverseName) {
      const fxResult = await crossMetaverseFxService.executeCrossMetaverseFx({
        sourceMetaverseNodeId: sourceDsez.node.nodeId,
        targetMetaverseNodeId: targetDsez.node.nodeId,
        sourceAmount: request.amount,
        sourceCurrency: request.currencyCode,
        targetCurrency: request.currencyCode,
        conversionMethod: request.conversionMethod || 'ssu',
      });
      fxTransactionId = fxResult.fxTransactionId;
    }

    // Step 4: Create bridge record
    const bridgeId = `BRIDGE-${uuidv4()}`;
    await prisma.metaverseBridge.create({
      data: {
        bridgeId,
        metaverseNodeId: sourceDsez.metaverseNodeId,
        bridgeType: 'multi_d_sez',
        virtualAssetId: request.assetId,
        amount: new Decimal(request.amount),
        currencyCode: request.currencyCode,
        status: 'active',
      },
    });

    logger.info('Multi-D-SEZ Bridge: Bridge created', {
      bridgeId,
      sourceDsezId: request.sourceDsezId,
      targetDsezId: request.targetDsezId,
    });

    return {
      bridgeId,
      status: 'active',
      fxTransactionId,
    };
  }

  /**
   * Get bridge by ID
   */
  async getBridge(bridgeId: string) {
    return await prisma.metaverseBridge.findUnique({
      where: { bridgeId },
      include: {
        node: true,
      },
    });
  }
}

export const multiDsezBridgeService = new MultiDsezBridgeService();

