// D-SEZ (Digital Sovereign Economic Zone) Service
// Supplement B: MetaverseDubai Integration Framework

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '@/infrastructure/monitoring/logger';
import {
  DigitalSovereignEconomicZoneRequest,
  DigitalSovereignEconomicZoneResult,
  DsezConfig,
} from './d-sez.model';


export class DsezService {
  /**
   * Create Digital Sovereign Economic Zone (D-SEZ)
   * MetaverseDubai is modeled as a D-SEZ with:
   * - Virtual citizenship/identity
   * - Digital land, assets, securities
   * - Tokenized intra-metaverse FX
   * - Real → virtual → real liquidity flows
   */
  async createDsez(
    request: DigitalSovereignEconomicZoneRequest
  ): Promise<DigitalSovereignEconomicZoneResult> {
    logger.info('D-SEZ: Creating Digital Sovereign Economic Zone', { request });

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

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

    const dsezId = `DSEZ-${uuidv4()}`;

    const dsez = await prisma.digitalSovereignEconomicZone.create({
      data: {
        dsezId,
        metaverseNodeId: request.metaverseNodeId,
        sovereignBankId: request.sovereignBankId || null,
        virtualCitizenshipEnabled:
          request.virtualCitizenshipEnabled ?? false,
        digitalLandEnabled: request.digitalLandEnabled ?? false,
        tokenizedFxEnabled: request.tokenizedFxEnabled ?? false,
        liquidityFlowEnabled: request.liquidityFlowEnabled ?? false,
        metadata: request.metadata || {},
        status: 'active',
      },
    });

    logger.info('D-SEZ: Digital Sovereign Economic Zone created', { dsezId });

    return {
      dsezId,
      metaverseNodeId: dsez.metaverseNodeId,
      status: dsez.status,
    };
  }

  /**
   * Get D-SEZ by ID
   */
  async getDsez(dsezId: string) {
    return await prisma.digitalSovereignEconomicZone.findUnique({
      where: { dsezId },
      include: {
        node: true,
        sovereignBank: true,
        rampTransactions: true,
        consistencyChecks: {
          orderBy: { createdAt: 'desc' },
          take: 10,
        },
      },
    });
  }

  /**
   * Get D-SEZ by metaverse node ID
   */
  async getDsezByNode(metaverseNodeId: string) {
    return await prisma.digitalSovereignEconomicZone.findFirst({
      where: { metaverseNodeId, status: 'active' },
      include: {
        node: true,
        sovereignBank: true,
      },
    });
  }

  /**
   * Get all active D-SEZs
   */
  async getAllDsezs() {
    return await prisma.digitalSovereignEconomicZone.findMany({
      where: { status: 'active' },
      include: {
        node: true,
        sovereignBank: true,
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Update D-SEZ configuration
   */
  async updateDsezConfig(
    dsezId: string,
    config: Partial<DsezConfig>
  ): Promise<DigitalSovereignEconomicZoneResult> {
    const dsez = await prisma.digitalSovereignEconomicZone.update({
      where: { dsezId },
      data: {
        ...(config.virtualCitizenshipEnabled !== undefined && {
          virtualCitizenshipEnabled: config.virtualCitizenshipEnabled,
        }),
        ...(config.digitalLandEnabled !== undefined && {
          digitalLandEnabled: config.digitalLandEnabled,
        }),
        ...(config.tokenizedFxEnabled !== undefined && {
          tokenizedFxEnabled: config.tokenizedFxEnabled,
        }),
        ...(config.liquidityFlowEnabled !== undefined && {
          liquidityFlowEnabled: config.liquidityFlowEnabled,
        }),
      },
    });

    return {
      dsezId: dsez.dsezId,
      metaverseNodeId: dsez.metaverseNodeId,
      status: dsez.status,
    };
  }

  /**
   * Suspend D-SEZ
   */
  async suspendDsez(dsezId: string): Promise<void> {
    await prisma.digitalSovereignEconomicZone.update({
      where: { dsezId },
      data: { status: 'suspended' },
    });

    logger.info('D-SEZ: Suspended', { dsezId });
  }

  /**
   * Activate D-SEZ
   */
  async activateDsez(dsezId: string): Promise<void> {
    await prisma.digitalSovereignEconomicZone.update({
      where: { dsezId },
      data: { status: 'active' },
    });

    logger.info('D-SEZ: Activated', { dsezId });
  }
}

export const dsezService = new DsezService();

