const db = require('../db');
// Removed circular dependency: const { sendLimitReachedEmail } = require('./emailService');

/**
 * Checks and increments the free tier limit for a user.
 * @param {number} userId 
 * @param {object} userObj (Optional) Existing user record
 * @returns {object} { allowed: boolean, limit: number, message: string }
 */
const enforceFreeTierLimit = async (userId, userObj = null) => {
    // 1. Get user if not provided
    let user = userObj;
    if (!user) {
        const userResult = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
        if (userResult.rows.length === 0) return { allowed: true }; 
        user = userResult.rows[0];
    }

    // 0. Pro/Monthly/Yearly plans are ALWAYS allowed
    if (['pro', 'monthly', 'yearly'].includes(user.subscription_plan)) {
        return { allowed: true };
    }

    // Check limit ONLY if user is on 'free' plan
    if ((user.role === 'normal' || user.role === 'user') && user.subscription_plan === 'free') {
        // 2. Organization Check (B2B Exemption)
        if (user.organization_id) {
            const orgResult = await db.query(
                "SELECT plan_type, trial_status FROM organizations WHERE id = ?",
                [user.organization_id]
            );
            if (orgResult.rows.length > 0) {
                const org = orgResult.rows[0];
                // If org has a paid plan OR an active trial, they get Pro features (unlimited alerts)
                if (org.plan_type === 'business' || org.plan_type === 'enterprise' || 
                   (org.plan_type === 'trial' && org.trial_status === 'active')) {
                    return { allowed: true };
                }
            }
        }

        const now = new Date();
        const lastReset = user.last_usage_reset ? new Date(user.last_usage_reset) : new Date();

        // Reset usage if month or year changed
        if (now.getMonth() !== lastReset.getMonth() || now.getFullYear() !== lastReset.getFullYear()) {
            await db.query('UPDATE users SET alerts_this_month = 0, last_usage_reset = ? WHERE id = ?', [now, userId]);
            user.alerts_this_month = 0;
        }

        // Fetch the free tier limit from system settings
        const limitResult = await db.query("SELECT value FROM system_settings WHERE `key` = 'free_tier_limit'");
        let limit = 3; // Default
        if (limitResult.rows.length > 0) {
            let rawVal = limitResult.rows[0].value;
            if (typeof rawVal === 'string') {
                rawVal = rawVal.replace(/^"|"$/g, '');
            }
            limit = parseInt(rawVal) || 3;
        }

        const currentUsage = user.alerts_this_month || 0;
        if (currentUsage >= limit) {
            // Check if we should send a nudge email (max once per week)
            const lastEmail = user.last_upgrade_email_at ? new Date(user.last_upgrade_email_at) : null;
            const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);

            if (!lastEmail || lastEmail < sevenDaysAgo) {
                // 1. Update timestamp FIRST to prevent parallel race conditions
                try {
                    await db.query('UPDATE users SET last_upgrade_email_at = NOW() WHERE id = ?', [userId]);
                    console.log(`[UsageService] Updated last_upgrade_email_at for user ${userId} to prevent spam.`);
                    
                    // 2. Send email asynchronously
                    const { sendLimitReachedEmail } = require('./emailService');
                    sendLimitReachedEmail(user.email, user.username || user.name, limit, userId)
                        .then(() => console.log(`[UsageService] Nudge email sent to ${user.email}`))
                        .catch(err => console.error('[UsageService] Failed to send limit email:', err));
                } catch (updateErr) {
                    // Log but don't crash - if the column is missing, we'll see this in logs.
                    // But we already fixed the column in the current terminal session.
                    console.error('[UsageService] Database update for last_upgrade_email_at FAILED:', updateErr.message);
                }
            }

            return { 
                allowed: false, 
                limit, 
                message: `Free tier limit reached (${limit} alerts/month). Please upgrade to Pro for unlimited access.` 
            };
        }

        // Increment usage
        await db.query('UPDATE users SET alerts_this_month = alerts_this_month + 1 WHERE id = ?', [userId]);
        return { allowed: true, limit };
    }

    // Not on free plan
    return { allowed: true };
};

module.exports = {
    enforceFreeTierLimit
};
