// DSCN Identity Verifier
import { Prisma } from '@prisma/client';
// Local identity verification

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '@/infrastructure/monitoring/logger';
import { gbigService } from '@/core/identity/gbig/gbig.service';


export interface IdentityVerificationRequest {
  nodeId: string;
  entityId: string;
  entityType: 'wallet' | 'account' | 'transaction';
}

export class DscnIdentityVerifierService {
  /**
   * Perform local identity verification
   */
  async performIdentityVerification(
    request: IdentityVerificationRequest
  ): Promise<{ resultId: string; scanResult: string; trustScore?: number }> {
    const resultId = `DSCN-ID-${uuidv4()}`;

    // Verify identity via GBIG
    try {
      // In production, would use GBIG service to verify identity
      // For now, simplified check
      const identityVerified = await this.verifyIdentity(request.entityId);

      const scanResult = identityVerified ? 'pass' : 'fail';
      const trustScore = identityVerified ? 80 : 0; // Default trust score

      // Create compliance result
      await prisma.dscnComplianceResult.create({
        data: {
          resultId,
          nodeId: request.nodeId,
          complianceType: 'identity_verification',
          entityId: request.entityId,
          entityType: request.entityType,
          scanResult,
          riskScore: trustScore > 0 ? 100 - trustScore : null, // Convert to risk score
          details: {
            verified: identityVerified,
            trustScore,
            verifiedAt: new Date().toISOString(),
          } as Prisma.InputJsonValue,
          status: 'pending',
          syncedToDbis: false,
        },
      });

      logger.info('DSCN Identity: Verification completed', {
        resultId,
        nodeId: request.nodeId,
        entityId: request.entityId,
        scanResult,
        trustScore,
      });

      return {
        resultId,
        scanResult,
        trustScore: trustScore > 0 ? trustScore : undefined,
      };
    } catch (error) {
      logger.error('DSCN Identity: Verification failed', { error, request });

      return {
        resultId,
        scanResult: 'fail',
      };
    }
  }

  /**
   * Verify identity (simplified)
   */
  private async verifyIdentity(entityId: string): Promise<boolean> {
    // In production, would query GBIG
    // For now, simplified check
    const account = await prisma.bankAccount.findFirst({
      where: {
        accountNumber: entityId,
        status: 'active',
      },
    });

    return account !== null;
  }
}

export const dscnIdentityVerifierService = new DscnIdentityVerifierService();

