// apps/api/src/utils/extractPhone.js

class PhoneExtractor {
    static extract(text) {
        const patterns = [
            // Kenyan numbers
            /(\+254|0)([7-9][0-9]{8})/g,
            // Tanzanian numbers
            /(\+255|0)([7-9][0-9]{8})/g,
            // Ugandan numbers
            /(\+256|0)([7-9][0-9]{8})/g,
            // International format
            /\+(?:[0-9] ?){6,14}[0-9]/g,
            // Local format with spaces/dashes
            /\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})/g,
            // Raw digits (10-15 digits)
            /\b[0-9]{10,15}\b/g
        ];
        
        for (const pattern of patterns) {
            const matches = text.match(pattern);
            if (matches && matches.length > 0) {
                const cleaned = this.clean(matches[0]);
                if (this.isValid(cleaned)) {
                    return cleaned;
                }
            }
        }
        
        return null;
    }
    
    static clean(phone) {
        return phone.replace(/[\s\-\(\)]/g, '');
    }
    
    static isValid(phone) {
        const digits = phone.replace(/\D/g, '');
        return digits.length >= 10 && digits.length <= 15;
    }
    
    static format(phone) {
        const cleaned = this.clean(phone);
        if (cleaned.startsWith('0') && cleaned.length === 10) {
            return '+254' + cleaned.substring(1);
        }
        if (cleaned.startsWith('254') && cleaned.length === 12) {
            return '+' + cleaned;
        }
        return cleaned;
    }
    
    static extractAll(text) {
        const phones = new Set();
        const patterns = [
            /(\+?254|0)[7-9][0-9]{8}/g,
            /(\+?255|0)[7-9][0-9]{8}/g,
            /(\+?256|0)[7-9][0-9]{8}/g,
            /\b[0-9]{10,15}\b/g
        ];
        
        for (const pattern of patterns) {
            const matches = text.match(pattern);
            if (matches) {
                matches.forEach(m => phones.add(this.clean(m)));
            }
        }
        
        return Array.from(phones);
    }
}

module.exports = PhoneExtractor;