// Cyber Threat Incident Management
// Creates and manages threat incidents for DCDC

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { defenseLayersService } from './defense-layers.service';


export interface ThreatIncidentRequest {
  threatType: string;
  threatCategory: string; // T1, T2, T3
  severity: string;
  sourceBankId?: string;
  targetBankId?: string;
  description: string;
  detectionMethod: string;
}

export class CyberThreatIncidentService {
  /**
   * Create threat incident
   */
  async createThreatIncident(request: ThreatIncidentRequest) {
    const incidentId = `INCIDENT-${uuidv4()}`;

    const incident = await prisma.cyberThreatIncident.create({
      data: {
        incidentId,
        threatType: request.threatType,
        threatCategory: request.threatCategory,
        severity: request.severity,
        sourceBankId: request.sourceBankId,
        targetBankId: request.targetBankId,
        description: request.description,
        detectionMethod: request.detectionMethod,
        status: 'detected',
        detectedAt: new Date(),
      },
    });

    // Automatically trigger defense layers for critical/high severity
    if (request.severity === 'critical' || request.severity === 'high') {
      await defenseLayersService.executeDefenseSequence(
        incidentId,
        request.threatType,
        request.severity,
        undefined,
        request.targetBankId
      );
    }

    return incident;
  }

  /**
   * Get threat incident
   */
  async getThreatIncident(incidentId: string) {
    return await prisma.cyberThreatIncident.findUnique({
      where: { incidentId },
      include: {
        actions: true,
        mitigations: true,
      },
    });
  }

  /**
   * Update threat incident status
   */
  async updateThreatStatus(
    incidentId: string,
    status: string,
    timestampField?: 'containedAt' | 'neutralizedAt' | 'resolvedAt'
  ) {
    const updateData: any = { status };

    if (timestampField) {
      updateData[timestampField] = new Date();
    }

    return await prisma.cyberThreatIncident.update({
      where: { incidentId },
      data: updateData,
    });
  }

  /**
   * Get active threats
   */
  async getActiveThreats() {
    return await prisma.cyberThreatIncident.findMany({
      where: {
        status: {
          in: ['detected', 'contained'],
        },
      },
      orderBy: {
        detectedAt: 'desc',
      },
    });
  }

  /**
   * Get threats by category
   */
  async getThreatsByCategory(category: string) {
    return await prisma.cyberThreatIncident.findMany({
      where: {
        threatCategory: category,
      },
      orderBy: {
        detectedAt: 'desc',
      },
    });
  }
}

export const cyberThreatIncidentService = new CyberThreatIncidentService();

