// Metaverse Identity Service
// Avatar-based identity anchoring (ILIE L3/L4)

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


export interface MetaverseIdentityRequest {
  metaverseNodeId: string;
  avatarId: string;
  identityLayer: 'L3' | 'L4'; // ILIE identity layers
  sovereignBankId?: string;
  identityData: any;
}

export interface MetaverseIdentityResult {
  identityId: string;
  avatarId: string;
  identityHash: string;
  status: string;
}

export class MetaverseIdentityService {
  /**
   * Create avatar-based identity anchoring
   * Links avatar to ILIE identity layers (L3/L4)
   */
  async createAvatarIdentity(
    request: MetaverseIdentityRequest
  ): Promise<MetaverseIdentityResult> {
    logger.info('Metaverse: Creating avatar identity', { request });

    // Step 1: 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}`);
    }

    // Step 2: Create identity hash
    const identityHash = this.createIdentityHash(request.identityData);

    // Step 3: Create identity record
    const identityId = `METAVERSE-ID-${uuidv4()}`;

    const identity = await prisma.metaverseIdentity.create({
      data: {
        identityId,
        metaverseNodeId: request.metaverseNodeId,
        avatarId: request.avatarId,
        identityLayer: request.identityLayer,
        sovereignBankId: request.sovereignBankId || null,
        identityHash,
        identityData: request.identityData as any,
        status: 'active',
      },
    });

    logger.info('Metaverse: Avatar identity created', {
      identityId,
      avatarId: request.avatarId,
    });

    return {
      identityId,
      avatarId: request.avatarId,
      identityHash,
      status: identity.status,
    };
  }

  /**
   * Create identity hash
   */
  private createIdentityHash(identityData: any): string {
    const dataString = JSON.stringify(identityData);
    return createHash('sha3-256').update(dataString).digest('hex');
  }

  /**
   * Get identity by ID
   */
  async getIdentity(identityId: string) {
    return await prisma.metaverseIdentity.findUnique({
      where: { identityId },
      include: {
        node: true,
      },
    });
  }

  /**
   * Get identity by avatar ID
   */
  async getIdentityByAvatar(avatarId: string) {
    return await prisma.metaverseIdentity.findFirst({
      where: { avatarId },
      include: {
        node: true,
      },
    });
  }

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

  /**
   * Verify identity integrity
   */
  async verifyIdentityIntegrity(identityId: string): Promise<boolean> {
    const identity = await prisma.metaverseIdentity.findUnique({
      where: { identityId },
    });

    if (!identity) {
      return false;
    }

    // Recalculate hash and verify
    const calculatedHash = this.createIdentityHash(identity.identityData as any);
    return calculatedHash === identity.identityHash;
  }
}

export const metaverseIdentityService = new MetaverseIdentityService();

