import { FilterXSS, whiteList } from 'xss';

/**
 * Sanitizes HTML content to prevent XSS attacks while allowing safe tags and attributes.
 * This is particularly important for content rendered with dangerouslySetInnerHTML.
 * 
 * @param html The raw HTML string to sanitize
 * @returns The sanitized HTML string
 */
export const sanitizeHtml = (html: string): string => {
    if (!html) return '';

    // Decode basic entities to prevent bypasses (e.g. &lt;script&gt;)
    // and ensuring we catch them during tag stripping
    const decoded = html
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&amp;/g, '&');
    
    // Custom options can be added here if we need to allow specific tags or attributes
    // For now, using default options which are quite secure
    // Custom options to restrict allowed tags
    // By NOT spreading ...whiteList, we explicitly only allow what we define
    const options = {
        whiteList: {
            // Text formatting
            'p': ['style', 'class'],
            'br': [],
            'b': [],
            'i': [],
            'u': [],
            'strong': [],
            'em': [],
            's': [],
            'strike': [],
            'del': [],
            'sub': [],
            'sup': [],
            'mark': [],
            'small': [],
            // Headings
            'h1': ['style', 'class'],
            'h2': ['style', 'class'],
            'h3': ['style', 'class'],
            'h4': ['style', 'class'],
            'h5': ['style', 'class'],
            'h6': ['style', 'class'],
            // Lists
            'ul': ['style', 'class'],
            'ol': ['style', 'class', 'start', 'type'],
            'li': ['style', 'class'],
            // Block elements
            'blockquote': ['style', 'class'],
            'pre': ['style', 'class'],
            'code': ['style', 'class'],
            'hr': [],
            'div': ['style', 'class'],
            'span': ['style', 'class'],
            // Tables
            'table': ['style', 'class', 'width', 'border', 'cellpadding', 'cellspacing'],
            'thead': ['style', 'class'],
            'tbody': ['style', 'class'],
            'tfoot': ['style', 'class'],
            'tr': ['style', 'class'],
            'th': ['style', 'class', 'colspan', 'rowspan'],
            'td': ['style', 'class', 'colspan', 'rowspan'],
            'caption': ['style', 'class'],
            'colgroup': [],
            'col': ['width'],
            // Links
            'a': ['href', 'title', 'target', 'rel'],
            // Images
            'img': ['src', 'alt', 'title', 'width', 'height'],
        },
        stripIgnoreTag: true,
        stripIgnoreTagBody: ['script']
    };

    const xssFilter = new FilterXSS(options);
    return xssFilter.process(decoded);
};

/**
 * STRICT Sanitization: Removes ALL HTML tags.
 * Use for titles, names, IDs, etc.
 * 
 * @param text The raw string to sanitize
 * @returns The sanitized string with all tags removed
 */
export const sanitizeStrict = (text: string): string => {
    if (!text) return '';
    
    // Decode basic entities to prevent bypasses
    const decoded = text
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&amp;/g, '&');

    const options = {
        whiteList: {}, // No tags allowed
        stripIgnoreTag: true,
        stripIgnoreTagBody: ['script', 'style', 'iframe', 'object', 'embed']
    };
    
    const xssFilter = new FilterXSS(options);
    return xssFilter.process(decoded);
};

/**
 * PERMISSIVE Sanitization: Allows safe formatting tags.
 * Use for rich-text fields (descriptions, comments).
 * Alias for the existing sanitizeHtml.
 * 
 * @param html The raw HTML string to sanitize
 * @returns The sanitized HTML string
 */
export const sanitizePermissive = (html: string): string => {
    return sanitizeHtml(html);
};

/**
 * Sanitizes an object by recursively sanitizing all string properties.
 * Useful for sanitizing request bodies or complex nested structures.
 * 
 * Uses field names to decide between strict and permissive sanitization.
 * 
 * @param obj The object to sanitize
 * @param richTextFields Set of keys that should use permissive sanitization
 * @returns The sanitized object
 */
export const sanitizeObject = <T>(obj: T, richTextFields: Set<string> = new Set([
    'description', 'requestDescription', 'comments', 'remarks', 'message', 'finalRemark', 
    'aiGeneratedRemark', 'remark', 'closingRemarks', 'alertSubmitForm16Template', 
    'reminderNotificationTemplate', 'templateRe', 'templateDealers', 'template'
])): T => {
    if (!obj || typeof obj !== 'object') return obj;

    if (Array.isArray(obj)) {
        return obj.map(item => sanitizeObject(item, richTextFields)) as any;
    }

    const sanitized: any = {};
    for (const [key, value] of Object.entries(obj)) {
        if (typeof value === 'string') {
            const isRichText = richTextFields.has(key);
            const sanitizedValue = isRichText ? sanitizePermissive(value) : sanitizeStrict(value);
            // If it's rich text and became effectively empty, keep it empty string for validation
            sanitized[key] = (isRichText && isHtmlEmpty(sanitizedValue)) ? '' : sanitizedValue;
        } else if (typeof value === 'object' && value !== null) {
            sanitized[key] = sanitizeObject(value, richTextFields);
        } else {
            sanitized[key] = value;
        }
    }

    return sanitized as T;
};

/**
 * Checks if HTML content is effectively empty (i.e., only whitespace or empty tags).
 * Useful for validating required rich-text fields after sanitization.
 * 
 * @param html The sanitized HTML string to check
 * @returns True if the HTML has no meaningful content (no text, no images)
 */
export const isHtmlEmpty = (html: string | null | undefined): boolean => {
    if (!html) return true;
    
    // First, check if there are any images (which are valid content but have no text)
    if (html.includes('<img')) return false;
    
    // Strip all HTML tags and trim
    const textOnly = html.replace(/<[^>]*>/g, '').trim();
    
    // Check for common non-breaking space and other entities that might stay after tag stripping
    const textWithoutEntities = textOnly
        .replace(/&nbsp;/g, '')
        .replace(/&zwj;/g, '')
        .replace(/&zwnj;/g, '')
        .replace(/&shy;/g, '')
        .trim();
        
    return textWithoutEntities === '';
};
