// apps/api/src/utils/extractEmail.js

class EmailExtractor {
    static extract(text) {
        const pattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
        const matches = text.match(pattern);
        
        if (matches && matches.length > 0) {
            return matches[0].toLowerCase();
        }
        
        return null;
    }
    
    static extractAll(text) {
        const pattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
        const matches = text.match(pattern);
        
        if (matches) {
            return [...new Set(matches.map(m => m.toLowerCase()))];
        }
        
        return [];
    }
    
    static isValid(email) {
        const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return pattern.test(email);
    }
    
    static getDomain(email) {
        if (!this.isValid(email)) return null;
        return email.split('@')[1];
    }
    
    static obfuscate(email) {
        if (!email) return '';
        const [local, domain] = email.split('@');
        if (local.length <= 2) return email;
        const obfuscated = local[0] + '***' + local[local.length - 1];
        return `${obfuscated}@${domain}`;
    }
}

module.exports = EmailExtractor;