const db = require('../db');

const checkTrialStatus = async (req, res, next) => {
    try {
        const orgId = req.params.id;
        
        // Skip if no ID
        if (!orgId) return next();

        const orgResult = await db.query('SELECT plan_type, trial_end_date, trial_status FROM organizations WHERE id = ?', [orgId]);
        
        if (orgResult.rows.length === 0) return next();
        
        const org = orgResult.rows[0];

        // If not a trial plan, skip check (assuming paid plans are fine)
        if (org.plan_type !== 'trial') {
            return next();
        }

        // Check if trial is expired based on date
        if (org.trial_end_date) {
            const now = new Date();
            const endDate = new Date(org.trial_end_date);
            
            // Allow a small grace period or strictly check
            if (endDate < now) {
                
                // Update status if not already marked (Sidebar/frontend might check this flag)
                if (org.trial_status !== 'expired') {
                    await db.query('UPDATE organizations SET trial_status = "expired" WHERE id = ?', [orgId]);
                }

                return res.status(403).json({ 
                    message: 'Your free trial has expired. Please upgrade your plan to continue using this feature.',
                    code: 'TRIAL_EXPIRED'
                });
            }
        }

        next();
    } catch (error) {
        console.error('Trial Check Middleware Error:', error);
        // Don't block on error, maybe just log and proceed or 500
        res.status(500).json({ message: 'Server error checking trial status' });
    }
};

module.exports = { checkTrialStatus };
