/**
 * Disposable Email Checker
 * 
 * Uses a local blocklist (from GitHub's disposable-email-domains project)
 * to detect and block registrations from temporary/disposable email providers.
 * 
 * The list is loaded once into memory at startup for O(1) lookup performance.
 */

const fs = require('fs');
const path = require('path');

let disposableDomains = null;

/**
 * Load the disposable domains list into a Set for fast lookup.
 * Called once at startup; subsequent calls return the cached Set.
 */
const loadDisposableDomains = () => {
    if (disposableDomains) return disposableDomains;

    try {
        const filePath = path.join(__dirname, '../data/disposable_domains.txt');
        const content = fs.readFileSync(filePath, 'utf-8');
        const domains = content
            .split('\n')
            .map(d => d.trim().toLowerCase())
            .filter(d => d.length > 0 && !d.startsWith('#'));
        
        disposableDomains = new Set(domains);
        console.log(`📧 Loaded ${disposableDomains.size} disposable email domains into memory.`);
        return disposableDomains;
    } catch (err) {
        console.error('⚠️ Could not load disposable domains list:', err.message);
        disposableDomains = new Set(); // Empty set — fail-open (allow all)
        return disposableDomains;
    }
};

/**
 * Check if an email address belongs to a disposable/temporary email provider.
 * @param {string} email - The email address to check
 * @returns {boolean} true if the email is disposable
 */
const isDisposableEmail = (email) => {
    if (!email || typeof email !== 'string') return false;

    const domains = loadDisposableDomains();
    const domain = email.toLowerCase().trim().split('@')[1];

    if (!domain) return false;

    return domains.has(domain);
};

/**
 * Get stats about the blocklist
 * @returns {{ totalDomains: number, loaded: boolean }}
 */
const getBlocklistStats = () => {
    const domains = loadDisposableDomains();
    return {
        totalDomains: domains.size,
        loaded: domains.size > 0
    };
};

module.exports = {
    isDisposableEmail,
    getBlocklistStats,
    loadDisposableDomains
};
