// Metaverse Settlement Service
// Virtual land settlement via GAS

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '@/infrastructure/monitoring/logger';
import { gasSettlementService } from '@/core/settlement/gas/gas-settlement.service';


export interface MetaverseSettlementRequest {
  metaverseNodeId: string;
  sourceBankId: string;
  destinationBankId: string;
  virtualLandId: string;
  amount: string;
  currencyCode: string;
  assetType: 'virtual_land' | 'virtual_asset' | 'nft';
}

export interface MetaverseSettlementResult {
  settlementId: string;
  gasSettlementId: string;
  virtualLandId: string;
  status: string;
}

export class MetaverseSettlementService {
  /**
   * Execute virtual land settlement via GAS
   */
  async executeVirtualLandSettlement(
    request: MetaverseSettlementRequest
  ): Promise<MetaverseSettlementResult> {
    logger.info('Metaverse: Executing virtual land settlement', { request });

    // Step 1: Verify metaverse node exists
    const node = await prisma.metaverse_nodes.findUnique({
      where: { nodeId: request.metaverseNodeId },
    });

    if (!node) {
      throw new Error(`Metaverse node not found: ${request.metaverseNodeId}`);
    }

    // Step 2: Execute settlement via GAS network
    const gasResult = await gasSettlementService.executeGasSettlement({
      sourceBankId: request.sourceBankId,
      destinationBankId: request.destinationBankId,
      amount: parseFloat(request.amount),
      currencyCode: request.currencyCode,
      assetType: request.assetType,
      networkType: 'multiversal',
    });

    // Step 3: Create metaverse settlement record
    const settlementId = `METAVERSE-SETTLE-${uuidv4()}`;

    const settlement = await prisma.metaverse_settlements.create({
      data: {
        id: uuidv4(),
        settlementId,
        metaverseNodeId: request.metaverseNodeId,
        gasSettlementId: gasResult.gasSettlementId,
        sourceBankId: request.sourceBankId,
        destinationBankId: request.destinationBankId,
        virtualLandId: request.virtualLandId,
        amount: new Decimal(request.amount),
        currencyCode: request.currencyCode,
        assetType: request.assetType,
        status: 'settled',
        settledAt: new Date(),
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    logger.info('Metaverse: Virtual land settlement completed', {
      settlementId,
      virtualLandId: request.virtualLandId,
    });

    return {
      settlementId,
      gasSettlementId: gasResult.gasSettlementId,
      virtualLandId: request.virtualLandId,
      status: settlement.status,
    };
  }

  /**
   * Get settlement by ID
   */
  async getSettlement(settlementId: string) {
    return await prisma.metaverse_settlements.findUnique({
      where: { settlementId },
      include: {
        node: true,
      },
    });
  }

  /**
   * Get settlements for metaverse node
   */
  async getSettlementsForNode(metaverseNodeId: string) {
    return await prisma.metaverse_settlements.findMany({
      where: { metaverseNodeId },
      orderBy: { createdAt: 'desc' },
    });
  }
}

export const metaverseSettlementService = new MetaverseSettlementService();

