/**
 * Security Toast Helper
 * Shows distinct, styled toast messages for antivirus/security scan errors.
 * Each error type (malware, file validation, XSS, scan unavailable) gets
 * its own clear message so the user knows exactly what happened.
 */

import { toast } from 'sonner';

// Security error codes returned by the backend
const SECURITY_ERROR_CODES = [
    'MALWARE_DETECTED',
    'FILE_VALIDATION_FAILED',
    'CONTENT_THREAT_DETECTED',
    'SCAN_UNAVAILABLE',
    'SCAN_ERROR',
] as const;

type SecurityErrorCode = typeof SECURITY_ERROR_CODES[number];

interface SecurityErrorResponse {
    error?: string;
    message?: string;
    details?: {
        errors?: string[];
        warnings?: string[];
        scanEngine?: string;
        signatures?: string[];
        scanType?: string;
        threats?: Array<{ description: string; severity: string }>;
    };
    scanEventId?: string;
}

// User-friendly titles for each error type
const ERROR_TITLES: Record<SecurityErrorCode, string> = {
    MALWARE_DETECTED: '🛑 Malware Detected',
    FILE_VALIDATION_FAILED: '⛔ File Rejected',
    CONTENT_THREAT_DETECTED: '⚠️ Malicious Content Detected',
    SCAN_UNAVAILABLE: '🔒 Security Scan Unavailable',
    SCAN_ERROR: '❌ Security Scan Error',
};

/**
 * Check if an API error response is a security/scan error.
 * Returns true if it was handled (showed a toast), false otherwise.
 */
export function handleSecurityError(error: any): boolean {
    const responseData: SecurityErrorResponse = error?.response?.data;
    if (!responseData?.error) return false;

    const errorCode = responseData.error as SecurityErrorCode;
    if (!SECURITY_ERROR_CODES.includes(errorCode)) return false;

    const title = ERROR_TITLES[errorCode] || 'Security Error';
    const message = responseData.message || 'File was blocked by security scan';

    // Build detail text
    let detailText = '';
    if (responseData.details) {
        if (responseData.details.signatures?.length) {
            detailText = `Virus: ${responseData.details.signatures.join(', ')}`;
        } else if (responseData.details.errors?.length) {
            detailText = responseData.details.errors[0] || '';
        } else if (responseData.details.threats?.length) {
            detailText = responseData.details.threats.map(t => t.description).join(', ');
        }
    }

    // Show custom styled toast
    toast.error(title, {
        description: detailText || message,
        duration: 8000,
        style: {
            background: '#fef2f2',
            border: '1px solid #fca5a5',
            color: '#991b1b',
        },
    });

    return true;
}
