// services/alert-reviewer.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Alert } from '../entity/alert.entity';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';

@Injectable()
export class AlertReviewerService {
  private readonly logger = new Logger(AlertReviewerService.name);

  constructor(
    private httpService: HttpService,
    private configService: ConfigService,
  ) {}

  // Process a reviewed alert with additional verification
  async processReview(alert: Alert): Promise<void> {
    if (!alert.isVerified) {
      this.logger.log(`Alert ${alert.id} marked as not verified, skipping additional verification`);
      return;
    }

    try {
      // Perform additional verification steps
      await this.checkAgainstThreatIntel(alert);
      await this.checkNepalRelevance(alert);

      this.logger.log(`Successfully processed review for alert ${alert.id}`);
    } catch (error) {
      this.logger.error(`Error processing review for alert ${alert.id}: ${error.message}`);
    }
  }

  // Check against threat intelligence platforms
  private async checkAgainstThreatIntel(alert: Alert): Promise<void> {
    try {
      // Example: Check URLs or IPs mentioned in the alert against VirusTotal
      const apiKey = this.configService.get<string>('VIRUS_TOTAL_API_KEY');

      // Extract potential URLs or IPs from the description
      const urlRegex = /(https?:\/\/[^\s]+)/g;
      const ipRegex = /\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/g;

      const urls = alert.description.match(urlRegex) || [];
      const ips = alert.description.match(ipRegex) || [];

      // Check URLs
      for (const url of urls) {
        try {
          const encodedUrl = encodeURIComponent(url);
          const response = await firstValueFrom(
            this.httpService.get(`https://www.virustotal.com/api/v3/urls/${encodedUrl}`, {
              headers: { 'x-apikey': apiKey },
            }),
          );

          const malicious = response.data.data.attributes.last_analysis_stats.malicious;
          if (malicious > 0) {
            // Update severity if malicious URLs are found
            alert.severity = Math.max(alert.severity || 0, 4);
            break;
          }
        } catch (error) {
          this.logger.warn(`Error checking URL ${url}: ${error.message}`);
        }
      }

      // Check IPs
      for (const ip of ips) {
        try {
          const response = await firstValueFrom(
            this.httpService.get(`https://www.virustotal.com/api/v3/ip_addresses/${ip}`, {
              headers: { 'x-apikey': apiKey },
            }),
          );

          const malicious = response.data.data.attributes.last_analysis_stats.malicious;
          if (malicious > 0) {
            // Update severity if malicious IPs are found
            alert.severity = Math.max(alert.severity || 0, 4);
            break;
          }
        } catch (error) {
          this.logger.warn(`Error checking IP ${ip}: ${error.message}`);
        }
      }
    } catch (error) {
      this.logger.error(`Error checking against threat intel: ${error.message}`);
    }
  }

  // Check relevance to Nepal
  private async checkNepalRelevance(alert: Alert): Promise<void> {
    try {
      // If already marked as relevant to Nepal, keep that setting
      if (alert.isRelevantToNepal) {
        return;
      }

      // Check if Nepal or Nepali organizations are mentioned in the alert
      const content = (alert.title + ' ' + alert.description).toLowerCase();
      const nepalKeywords = [
        'nepal',
        'nepali',
        'kathmandu',
        'pokhara',
        'np',
        'ncert',
        'nepal cert',
        'nepali bank',
        'nepal telecom',
        'ntc',
        'ncell',
        'worldlink',
        'nepal government',
      ];

      for (const keyword of nepalKeywords) {
        if (content.includes(keyword)) {
          alert.isRelevantToNepal = true;
          this.logger.log(`Alert ${alert.id} marked as relevant to Nepal based on keyword '${keyword}'`);
          break;
        }
      }

      // If the target country is Nepal, mark as relevant
      if (alert.targetCountry && (alert.targetCountry === 'Nepal' || alert.targetCountry.includes('Nepal') || alert.targetCountry.includes('NP'))) {
        alert.isRelevantToNepal = true;
        this.logger.log(`Alert ${alert.id} marked as relevant to Nepal based on target country`);
      }

      // Check for Nepali organizations
      if (alert.targetOrganization) {
        const nepaliOrgKeywords = [
          'nepal bank',
          'nepal telecom',
          'ntc',
          'ncell',
          'worldlink',
          'nepal government',
          'nepal army',
          'nepali',
          'kathmandu',
          'pokhara',
        ];

        for (const keyword of nepaliOrgKeywords) {
          if (alert.targetOrganization.toLowerCase().includes(keyword)) {
            alert.isRelevantToNepal = true;
            this.logger.log(`Alert ${alert.id} marked as relevant to Nepal based on organization '${keyword}'`);
            break;
          }
        }
      }
    } catch (error) {
      this.logger.error(`Error checking Nepal relevance: ${error.message}`);
    }
  }
}
