// Avatar Identity Anchor Service
// Anchor avatar to ILIE L3/L4
// Supplement B: MetaverseDubai Integration Framework

import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';
import { ilieService } from '@/core/identity/ilie/ilie.service';


export interface AvatarIdentityAnchorRequest {
  metaverseNodeId: string;
  avatarId: string;
  ilieIdentityId: string;
  identityLayer: 'L3' | 'L4';
}

export interface AvatarIdentityAnchorResult {
  anchored: boolean;
  avatarIdentityId: string;
  ilieIdentityId: string;
}

export class AvatarIdentityAnchorService {
  /**
   * Anchor avatar identity to ILIE L3/L4
   */
  async anchorAvatarIdentity(
    request: AvatarIdentityAnchorRequest
  ): Promise<AvatarIdentityAnchorResult> {
    logger.info('Avatar Identity Anchor: Anchoring avatar identity', {
      request,
    });

    // Step 1: Verify ILIE identity exists
    const ilieIdentity = await ilieService.getInfiniteIdentity(
      request.ilieIdentityId
    );

    if (!ilieIdentity) {
      throw new Error(`ILIE identity not found: ${request.ilieIdentityId}`);
    }

    // Step 2: Get or create avatar identity
    let avatarIdentity = await prisma.metaverseIdentity.findFirst({
      where: {
        metaverseNodeId: request.metaverseNodeId,
        avatarId: request.avatarId,
        identityLayer: request.identityLayer,
      },
    });

    if (!avatarIdentity) {
      // Create new avatar identity
      avatarIdentity = await prisma.metaverseIdentity.create({
        data: {
          identityId: `AVATAR-ID-${Date.now()}`,
          metaverseNodeId: request.metaverseNodeId,
          avatarId: request.avatarId,
          identityLayer: request.identityLayer,
          identityHash: this.generateIdentityHash({
            avatarId: request.avatarId,
            ilieIdentityId: request.ilieIdentityId,
          }),
          identityData: {
            ilieIdentityId: request.ilieIdentityId,
            anchored: true,
          },
          status: 'active',
        },
      });
    } else {
      // Update existing avatar identity
      avatarIdentity = await prisma.metaverseIdentity.update({
        where: { identityId: avatarIdentity.identityId },
        data: {
          identityData: {
            ...(avatarIdentity.identityData as Record<string, unknown>),
            ilieIdentityId: request.ilieIdentityId,
            anchored: true,
          },
        },
      });
    }

    logger.info('Avatar Identity Anchor: Avatar identity anchored', {
      avatarIdentityId: avatarIdentity.identityId,
      ilieIdentityId: request.ilieIdentityId,
    });

    return {
      anchored: true,
      avatarIdentityId: avatarIdentity.identityId,
      ilieIdentityId: request.ilieIdentityId,
    };
  }

  /**
   * Generate identity hash
   */
  private generateIdentityHash(data: Record<string, unknown>): string {
    const crypto = require('crypto');
    const hash = crypto.createHash('sha256');
    hash.update(JSON.stringify(data));
    return hash.digest('hex');
  }
}

export const avatarIdentityAnchorService = new AvatarIdentityAnchorService();

