const Translation = require('../models/translation.model');

// ============================================================================
// Language Middleware
// Extracts language from request and attaches to req object
// Sources: Header > Query > Cookie > Default from settings
// ============================================================================

/**
 * Language detection middleware
 * Attaches req.language with the detected language code
 */
const detectLanguage = async (req, res, next) => {
    try {
        // Priority 1: Accept-Language header (custom header for API)
        let language = req.headers['x-language'] || req.headers['accept-language'];

        // Priority 2: Query parameter
        if (!language) {
            language = req.query.lang || req.query.language;
        }

        // Priority 3: Cookie
        if (!language) {
            language = req.cookies?.app_language;
        }

        // Priority 4: Default from settings (fetched once, cached)
        if (!language) {
            language = await getDefaultLanguage();
        }

        // Normalize and validate
        language = normalizeLanguage(language);

        // Attach to request
        req.language = language;

        // DEBUG: Log detected language for user verification
        // console.log(`[Language] ${req.method} ${req.originalUrl || req.url} -> Detected: '${language}'`);

        // Attach helper method
        req.isDefaultLanguage = () => language === 'en';

        next();
    } catch (error) {
        console.error('[LanguageMiddleware] Error:', error);
        req.language = 'en';
        next();
    }
};

// ============================================================================
// Language Helper Utilities
// ============================================================================

// Supported languages
const SUPPORTED_LANGUAGES = ['en', 'hi', 'fr', 'de', 'ar', 'es'];

// Default language (can be overridden by settings)
let cachedDefaultLanguage = 'en';
let cacheTime = 0;
let isRefreshing = false;
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

/**
 * Get default language from settings (with caching)
 */
const getDefaultLanguage = async () => {
    const now = Date.now();

    // Return cached value if still valid
    if (now - cacheTime < CACHE_TTL) {
        return cachedDefaultLanguage;
    }

    // If another request is already refreshing, return cached value
    if (isRefreshing) {
        return cachedDefaultLanguage;
    }

    isRefreshing = true;

    try {
        const Setting = require('../models/setting.model');
        const settings = await Setting.findOne().select('language.defaultLanguage').lean();

        if (settings?.language?.defaultLanguage) {
            cachedDefaultLanguage = settings.language.defaultLanguage;
        }
        cacheTime = now;
    } catch (error) {
        console.error('[LanguageMiddleware] Failed to fetch default language:', error);
    } finally {
        isRefreshing = false;
    }

    return cachedDefaultLanguage;
};

/**
 * Normalize language code
 */
const normalizeLanguage = (lang) => {
    if (!lang) return 'en';

    // Handle full locale (e.g., 'en-US' -> 'en')
    const code = lang.toLowerCase().split('-')[0].split('_')[0].trim();

    // Validate against supported languages
    return SUPPORTED_LANGUAGES.includes(code) ? code : 'en';
};

/**
 * Invalidate cached default language
 * Call this when language settings are updated
 */
const invalidateLanguageCache = () => {
    cacheTime = 0;
};

module.exports = {
    detectLanguage,
    getDefaultLanguage,
    normalizeLanguage,
    invalidateLanguageCache,
    SUPPORTED_LANGUAGES
};
