// DSCN AML Scanner
// Local AML scanning

import { v4 as uuidv4 } from 'uuid';
import { logger } from '@/infrastructure/monitoring/logger';
import { amlVelocityEngineService } from '@/core/compliance/ai/aml-velocity-engine.service';
import { Prisma } from '@prisma/client';
import prisma from '@/shared/database/prisma';

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

export class DscnAmlScannerService {
  /**
   * Perform local AML scan
   */
  async performAmlScan(request: AmlScanRequest): Promise<{ resultId: string; scanResult: string; riskScore?: number }> {
    const resultId = `DSCN-AML-${uuidv4()}`;

    // Perform AML checks
    const amlAnomalies = await amlVelocityEngineService.detectVelocityAnomalies(
      request.entityId,
      request.entityType,
      3600000 // 1 hour
    );

    // Calculate risk score
    const riskScore = amlAnomalies.length > 0
      ? amlAnomalies.reduce((sum: number, anomaly: { anomalyScore?: number }) => sum + (anomaly.anomalyScore ?? 0), 0) / amlAnomalies.length
      : 0;

    // Determine scan result
    const scanResult = riskScore > 70 ? 'fail' : riskScore > 40 ? 'review_required' : 'pass';

    // Create compliance result
    await prisma.dscn_compliance_results.create({
      data: {
        id: uuidv4(),
        resultId,
        nodeId: request.nodeId,
        complianceType: 'aml_scan',
        entityId: request.entityId,
        entityType: request.entityType,
        scanResult,
        riskScore: riskScore > 0 ? riskScore : null,
        details: {
          anomalies: amlAnomalies,
          riskScore,
        } as unknown as Prisma.InputJsonValue,
        status: 'pending',
          syncedToDbis: false,
          createdAt: new Date(),
          updatedAt: new Date(),
        },
    });

    logger.info('DSCN AML: Scan completed', {
      resultId,
      nodeId: request.nodeId,
      entityId: request.entityId,
      scanResult,
      riskScore,
    });

    return {
      resultId,
      scanResult,
      riskScore: riskScore > 0 ? riskScore : undefined,
    };
  }
}

export const dscnAmlScannerService = new DscnAmlScannerService();

