/**
 * Security Alert Emails Service
 *
 * Sends email notifications when security vulnerabilities are detected
 *
 * @module services/security-alert-emails
 */

import { sendEmail } from '@/lib/email';
import { logger } from '@/lib/logger';
import type {
  SecurityScanResult,
  Vulnerability,
  VulnerabilitySeverity,
} from '@/lib/types/security-scanner.types';

/**
 * Alert configuration
 */
const ALERT_CONFIG = {
  defaultRecipient: 'asimali06@hotmail.com',
  criticalSubjectPrefix: '[CRITICAL SECURITY ALERT]',
  highSubjectPrefix: '[SECURITY ALERT]',
  summarySubjectPrefix: '[Security Scan Report]',
};

/**
 * Severity colors for email
 */
const SEVERITY_COLORS: Record<VulnerabilitySeverity, string> = {
  critical: '#dc2626',
  high: '#ea580c',
  medium: '#ca8a04',
  low: '#2563eb',
  info: '#6b7280',
};

/**
 * Severity badges for email
 */
const SEVERITY_BADGES: Record<VulnerabilitySeverity, string> = {
  critical: 'CRITICAL',
  high: 'HIGH',
  medium: 'MEDIUM',
  low: 'LOW',
  info: 'INFO',
};

/**
 * Security Alert Emails Service
 */
export class SecurityAlertEmailsService {
  /**
   * Send an immediate alert for critical/high vulnerabilities
   */
  async sendImmediateAlert(
    scanResult: SecurityScanResult,
    recipient: string = ALERT_CONFIG.defaultRecipient
  ): Promise<boolean> {
    const criticalVulns = scanResult.vulnerabilities.filter(
      (v) => v.severity === 'critical' || v.severity === 'high'
    );

    if (criticalVulns.length === 0) {
      logger.debug('No critical/high vulnerabilities to alert about');
      return true;
    }

    const hasCritical = criticalVulns.some((v) => v.severity === 'critical');
    const subject = `${hasCritical ? ALERT_CONFIG.criticalSubjectPrefix : ALERT_CONFIG.highSubjectPrefix} Mawidi Security - ${criticalVulns.length} vulnerability(ies) detected`;

    const html = this.generateImmediateAlertHTML(scanResult, criticalVulns);
    const text = this.generateImmediateAlertText(scanResult, criticalVulns);

    try {
      const success = await sendEmail(recipient, { subject, html, text });

      if (success) {
        logger.info('Security alert email sent', {
          recipient,
          vulnerabilityCount: criticalVulns.length,
          hasCritical,
        });
      }

      return success;
    } catch (error) {
      logger.error('Failed to send security alert email', {
        error: error instanceof Error ? error.message : String(error),
        recipient,
      });
      return false;
    }
  }

  /**
   * Send a summary report email
   */
  async sendSummaryReport(
    scanResult: SecurityScanResult,
    recipient: string = ALERT_CONFIG.defaultRecipient
  ): Promise<boolean> {
    const subject = `${ALERT_CONFIG.summarySubjectPrefix} Mawidi - Score: ${scanResult.summary.securityScore}/100 | Risk: ${scanResult.summary.riskLevel.toUpperCase()}`;

    const html = this.generateSummaryReportHTML(scanResult);
    const text = this.generateSummaryReportText(scanResult);

    try {
      const success = await sendEmail(recipient, { subject, html, text });

      if (success) {
        logger.info('Security summary report sent', {
          recipient,
          securityScore: scanResult.summary.securityScore,
          riskLevel: scanResult.summary.riskLevel,
        });
      }

      return success;
    } catch (error) {
      logger.error('Failed to send security summary email', {
        error: error instanceof Error ? error.message : String(error),
        recipient,
      });
      return false;
    }
  }

  /**
   * Generate HTML for immediate alert
   */
  private generateImmediateAlertHTML(
    scanResult: SecurityScanResult,
    criticalVulns: Vulnerability[]
  ): string {
    const hasCritical = criticalVulns.some((v) => v.severity === 'critical');
    const headerColor = hasCritical ? '#dc2626' : '#ea580c';

    const vulnRows = criticalVulns
      .map(
        (v) => `
        <tr>
          <td style="padding: 16px; border-bottom: 1px solid #e5e7eb;">
            <div style="display: flex; align-items: flex-start; gap: 12px;">
              <span style="
                display: inline-block;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 11px;
                font-weight: 700;
                color: white;
                background-color: ${SEVERITY_COLORS[v.severity]};
                text-transform: uppercase;
              ">${SEVERITY_BADGES[v.severity]}</span>
              <div style="flex: 1;">
                <div style="font-weight: 600; color: #1f2937; margin-bottom: 4px;">${v.title}</div>
                <div style="font-size: 14px; color: #4b5563; margin-bottom: 8px;">${v.description}</div>
                <div style="font-size: 13px; color: #6b7280;">
                  <strong>Category:</strong> ${v.category} |
                  <strong>Affected:</strong> ${v.affectedResources.join(', ')}
                </div>
                <div style="margin-top: 8px; padding: 12px; background: #fef3c7; border-radius: 6px;">
                  <strong style="color: #92400e;">Remediation:</strong>
                  <span style="color: #78350f;">${v.remediation}</span>
                </div>
              </div>
            </div>
          </td>
        </tr>
      `
      )
      .join('');

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Security Alert</title>
      </head>
      <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; background-color: #f3f4f6;">
        <div style="max-width: 700px; margin: 0 auto; padding: 20px;">
          <div style="background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
            <!-- Header -->
            <div style="background: ${headerColor}; color: white; padding: 30px; text-align: center;">
              <div style="font-size: 48px; margin-bottom: 10px;">
                ${hasCritical ? '🚨' : '⚠️'}
              </div>
              <h1 style="margin: 0; font-size: 24px; font-weight: 700;">
                ${hasCritical ? 'CRITICAL SECURITY ALERT' : 'SECURITY ALERT'}
              </h1>
              <p style="margin: 10px 0 0 0; opacity: 0.9;">
                ${criticalVulns.length} vulnerability${criticalVulns.length > 1 ? 'ies' : 'y'} detected on Mawidi
              </p>
            </div>

            <!-- Summary -->
            <div style="padding: 24px; background: #fef2f2; border-bottom: 1px solid #fecaca;">
              <table style="width: 100%; border-collapse: collapse;">
                <tr>
                  <td style="padding: 8px 0;">
                    <span style="color: #6b7280;">Scan Time:</span>
                    <strong style="color: #1f2937;">${scanResult.completedAt.toLocaleString()}</strong>
                  </td>
                  <td style="padding: 8px 0; text-align: right;">
                    <span style="color: #6b7280;">Environment:</span>
                    <strong style="color: #1f2937;">${scanResult.environment.toUpperCase()}</strong>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 8px 0;">
                    <span style="color: #6b7280;">Security Score:</span>
                    <strong style="color: ${scanResult.summary.securityScore < 70 ? '#dc2626' : '#059669'};">
                      ${scanResult.summary.securityScore}/100
                    </strong>
                  </td>
                  <td style="padding: 8px 0; text-align: right;">
                    <span style="color: #6b7280;">Risk Level:</span>
                    <strong style="color: ${headerColor};">${scanResult.summary.riskLevel.toUpperCase()}</strong>
                  </td>
                </tr>
              </table>
            </div>

            <!-- Vulnerabilities -->
            <div style="padding: 24px;">
              <h2 style="margin: 0 0 16px 0; font-size: 18px; color: #1f2937;">
                Vulnerabilities Requiring Immediate Attention
              </h2>
              <table style="width: 100%; border-collapse: collapse; border: 1px solid #e5e7eb; border-radius: 8px; overflow: hidden;">
                ${vulnRows}
              </table>
            </div>

            <!-- Action Required -->
            <div style="padding: 24px; background: #fef3c7; border-top: 1px solid #fcd34d;">
              <h3 style="margin: 0 0 12px 0; color: #92400e;">
                ⚡ Immediate Action Required
              </h3>
              <p style="margin: 0; color: #78350f; font-size: 14px;">
                These vulnerabilities pose a significant risk to your application security.
                Please review and address them as soon as possible.
              </p>
            </div>

            <!-- Footer -->
            <div style="padding: 20px; background: #f9fafb; text-align: center; border-top: 1px solid #e5e7eb;">
              <p style="margin: 0; color: #6b7280; font-size: 12px;">
                Mawidi Security Scanner v${scanResult.scannerVersion} |
                Scan ID: ${scanResult.scanId}
              </p>
              <p style="margin: 8px 0 0 0; color: #9ca3af; font-size: 11px;">
                This is an automated security alert from your Mawidi security monitoring system.
              </p>
            </div>
          </div>
        </div>
      </body>
      </html>
    `;
  }

  /**
   * Generate plain text for immediate alert
   */
  private generateImmediateAlertText(
    scanResult: SecurityScanResult,
    criticalVulns: Vulnerability[]
  ): string {
    const hasCritical = criticalVulns.some((v) => v.severity === 'critical');

    let text = `
${hasCritical ? '🚨 CRITICAL SECURITY ALERT' : '⚠️ SECURITY ALERT'}
==========================================

${criticalVulns.length} vulnerability(ies) detected on Mawidi

Scan Time: ${scanResult.completedAt.toLocaleString()}
Environment: ${scanResult.environment.toUpperCase()}
Security Score: ${scanResult.summary.securityScore}/100
Risk Level: ${scanResult.summary.riskLevel.toUpperCase()}

VULNERABILITIES:
----------------
`;

    for (const v of criticalVulns) {
      text += `
[${v.severity.toUpperCase()}] ${v.title}
  Description: ${v.description}
  Category: ${v.category}
  Affected: ${v.affectedResources.join(', ')}
  Remediation: ${v.remediation}
`;
    }

    text += `
==========================================
Mawidi Security Scanner v${scanResult.scannerVersion}
Scan ID: ${scanResult.scanId}
`;

    return text;
  }

  /**
   * Generate HTML for summary report
   */
  private generateSummaryReportHTML(scanResult: SecurityScanResult): string {
    const { summary } = scanResult;
    const scoreColor =
      summary.securityScore >= 80
        ? '#059669'
        : summary.securityScore >= 60
          ? '#ca8a04'
          : '#dc2626';

    const riskColors: Record<string, string> = {
      critical: '#dc2626',
      high: '#ea580c',
      medium: '#ca8a04',
      low: '#2563eb',
      minimal: '#059669',
    };

    const vulnSummary = Object.entries(summary.vulnerabilities)
      .filter(([, count]) => (count as number) > 0)
      .map(
        ([severity, count]) => `
        <div style="display: inline-block; margin: 4px; padding: 8px 12px; border-radius: 6px; background: ${SEVERITY_COLORS[severity as VulnerabilitySeverity]}20; border: 1px solid ${SEVERITY_COLORS[severity as VulnerabilitySeverity]};">
          <span style="font-weight: 700; color: ${SEVERITY_COLORS[severity as VulnerabilitySeverity]};">${count}</span>
          <span style="color: #4b5563; font-size: 13px;">${severity}</span>
        </div>
      `
      )
      .join('');

    const failedChecks = scanResult.checks.filter((c) => c.status === 'fail');
    const warningChecks = scanResult.checks.filter((c) => c.status === 'warning');

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Security Scan Report</title>
      </head>
      <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; background-color: #f3f4f6;">
        <div style="max-width: 700px; margin: 0 auto; padding: 20px;">
          <div style="background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
            <!-- Header -->
            <div style="background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%); color: white; padding: 30px; text-align: center;">
              <div style="font-size: 48px; margin-bottom: 10px;">🔒</div>
              <h1 style="margin: 0; font-size: 24px; font-weight: 700;">Security Scan Report</h1>
              <p style="margin: 10px 0 0 0; opacity: 0.9;">
                Mawidi - ${scanResult.completedAt.toLocaleDateString()}
              </p>
            </div>

            <!-- Score Card -->
            <div style="padding: 30px; text-align: center; border-bottom: 1px solid #e5e7eb;">
              <div style="display: inline-block; width: 120px; height: 120px; border-radius: 50%; background: ${scoreColor}15; border: 4px solid ${scoreColor}; display: flex; align-items: center; justify-content: center;">
                <div>
                  <div style="font-size: 36px; font-weight: 700; color: ${scoreColor};">${summary.securityScore}</div>
                  <div style="font-size: 12px; color: #6b7280;">SCORE</div>
                </div>
              </div>
              <div style="margin-top: 16px;">
                <span style="
                  display: inline-block;
                  padding: 6px 16px;
                  border-radius: 20px;
                  font-size: 14px;
                  font-weight: 600;
                  color: white;
                  background: ${riskColors[summary.riskLevel]};
                ">
                  ${summary.riskLevel.toUpperCase()} RISK
                </span>
              </div>
            </div>

            <!-- Quick Stats -->
            <div style="padding: 24px; background: #f9fafb;">
              <div style="display: flex; justify-content: space-around; text-align: center;">
                <div>
                  <div style="font-size: 28px; font-weight: 700; color: #059669;">${summary.passed}</div>
                  <div style="font-size: 13px; color: #6b7280;">Passed</div>
                </div>
                <div>
                  <div style="font-size: 28px; font-weight: 700; color: #dc2626;">${summary.failed}</div>
                  <div style="font-size: 13px; color: #6b7280;">Failed</div>
                </div>
                <div>
                  <div style="font-size: 28px; font-weight: 700; color: #ca8a04;">${summary.warnings}</div>
                  <div style="font-size: 13px; color: #6b7280;">Warnings</div>
                </div>
                <div>
                  <div style="font-size: 28px; font-weight: 700; color: #6b7280;">${summary.totalChecks}</div>
                  <div style="font-size: 13px; color: #6b7280;">Total Checks</div>
                </div>
              </div>
            </div>

            <!-- Vulnerabilities Summary -->
            ${
              vulnSummary
                ? `
            <div style="padding: 24px;">
              <h3 style="margin: 0 0 16px 0; color: #1f2937;">Vulnerabilities by Severity</h3>
              <div>${vulnSummary}</div>
            </div>
            `
                : ''
            }

            <!-- Failed Checks -->
            ${
              failedChecks.length > 0
                ? `
            <div style="padding: 24px; border-top: 1px solid #e5e7eb;">
              <h3 style="margin: 0 0 16px 0; color: #dc2626;">❌ Failed Checks (${failedChecks.length})</h3>
              <ul style="margin: 0; padding-left: 20px; color: #4b5563;">
                ${failedChecks.map((c) => `<li style="margin-bottom: 8px;"><strong>${c.name}</strong>: ${c.details || c.description}</li>`).join('')}
              </ul>
            </div>
            `
                : ''
            }

            <!-- Warnings -->
            ${
              warningChecks.length > 0
                ? `
            <div style="padding: 24px; border-top: 1px solid #e5e7eb;">
              <h3 style="margin: 0 0 16px 0; color: #ca8a04;">⚠️ Warnings (${warningChecks.length})</h3>
              <ul style="margin: 0; padding-left: 20px; color: #4b5563;">
                ${warningChecks.map((c) => `<li style="margin-bottom: 8px;"><strong>${c.name}</strong>: ${c.details || c.description}</li>`).join('')}
              </ul>
            </div>
            `
                : ''
            }

            <!-- Scan Details -->
            <div style="padding: 24px; background: #f9fafb; border-top: 1px solid #e5e7eb;">
              <h3 style="margin: 0 0 12px 0; color: #1f2937;">Scan Details</h3>
              <table style="width: 100%; font-size: 14px;">
                <tr>
                  <td style="padding: 4px 0; color: #6b7280;">Environment:</td>
                  <td style="padding: 4px 0; color: #1f2937; text-align: right;">${scanResult.environment}</td>
                </tr>
                <tr>
                  <td style="padding: 4px 0; color: #6b7280;">Base URL:</td>
                  <td style="padding: 4px 0; color: #1f2937; text-align: right;">${scanResult.baseUrl}</td>
                </tr>
                <tr>
                  <td style="padding: 4px 0; color: #6b7280;">Duration:</td>
                  <td style="padding: 4px 0; color: #1f2937; text-align: right;">${(scanResult.duration / 1000).toFixed(2)}s</td>
                </tr>
                <tr>
                  <td style="padding: 4px 0; color: #6b7280;">Scanner Version:</td>
                  <td style="padding: 4px 0; color: #1f2937; text-align: right;">v${scanResult.scannerVersion}</td>
                </tr>
              </table>
            </div>

            <!-- Footer -->
            <div style="padding: 20px; text-align: center; border-top: 1px solid #e5e7eb;">
              <p style="margin: 0; color: #6b7280; font-size: 12px;">
                Scan ID: ${scanResult.scanId}
              </p>
              <p style="margin: 8px 0 0 0; color: #9ca3af; font-size: 11px;">
                This is an automated security report from Mawidi Security Scanner.
              </p>
            </div>
          </div>
        </div>
      </body>
      </html>
    `;
  }

  /**
   * Generate plain text for summary report
   */
  private generateSummaryReportText(scanResult: SecurityScanResult): string {
    const { summary } = scanResult;

    let text = `
🔒 MAWIDI SECURITY SCAN REPORT
==========================================

Security Score: ${summary.securityScore}/100
Risk Level: ${summary.riskLevel.toUpperCase()}

SUMMARY
-------
✅ Passed: ${summary.passed}
❌ Failed: ${summary.failed}
⚠️ Warnings: ${summary.warnings}
📊 Total Checks: ${summary.totalChecks}

VULNERABILITIES
---------------
Critical: ${summary.vulnerabilities.critical}
High: ${summary.vulnerabilities.high}
Medium: ${summary.vulnerabilities.medium}
Low: ${summary.vulnerabilities.low}
Info: ${summary.vulnerabilities.info}
`;

    const failedChecks = scanResult.checks.filter((c) => c.status === 'fail');
    if (failedChecks.length > 0) {
      text += `
FAILED CHECKS
-------------
${failedChecks.map((c) => `- ${c.name}: ${c.details || c.description}`).join('\n')}
`;
    }

    text += `
SCAN DETAILS
------------
Environment: ${scanResult.environment}
Base URL: ${scanResult.baseUrl}
Duration: ${(scanResult.duration / 1000).toFixed(2)}s
Scanner Version: v${scanResult.scannerVersion}
Scan ID: ${scanResult.scanId}

==========================================
`;

    return text;
  }
}

// Export singleton
export const securityAlertEmailsService = new SecurityAlertEmailsService();
