// apps/api/src/middleware/checkCredits.js

const { DatabaseClient } = require('../../../../packages/db/client');
const db = new DatabaseClient();

async function checkCredits(req, res, next) {
    try {
        const userId = req.user.id;
        const user = await db.get('SELECT plan, daily_credits, credits_reset_date FROM users WHERE id = ?', [userId]);

        if (!user) return res.status(401).json({ error: 'User not found' });

        if (user.plan === 'pro') {
            return next();
        }

        const today = new Date().toISOString().split('T')[0];
        const resetDate = user.credits_reset_date
            ? new Date(user.credits_reset_date).toISOString().split('T')[0]
            : null;

        if (resetDate !== today) {
            const freeLimit = await db.get(
                'SELECT setting_value FROM system_settings WHERE setting_key = ?',
                ['free_daily_limit']
            );

            const limit = freeLimit ? parseInt(freeLimit.setting_value, 10) : 5;

            await db.run(
                'UPDATE users SET daily_credits = ?, credits_reset_date = ? WHERE id = ?',
                [limit, today, userId]
            );

            user.daily_credits = limit;
        }

        if (user.daily_credits <= 0) {
            return res.status(403).json({
                error: 'Daily free limit reached. Upgrade to Pro for unlimited signals.',
                code: 'LIMIT_REACHED',
                upgradeRequired: true
            });
        }

        req.availableCredits = user.daily_credits;
        next();
    } catch (error) {
        console.error('Credit check error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
}

module.exports = checkCredits;