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

exports.getStats = async (req, res) => {
    try {
        const userId = req.user.id;

        // Get user's own referral code
        const userRes = await db.query('SELECT referral_code FROM users WHERE id = ?', [userId]);
        const referralCode = userRes.rows[0]?.referral_code;

        // Get stats and list of invited users
        const statsRes = await db.query(`
            SELECT 
                r.id,
                r.status,
                r.created_at,
                u.email
            FROM referrals r
            JOIN users u ON r.referee_id = u.id
            WHERE r.referrer_id = ?
            ORDER BY r.created_at DESC
        `, [userId]);

        // Mask emails for privacy (e.g., j***o@gmail.com)
        const invites = statsRes.rows.map(row => {
            const [localPart, domain] = row.email.split('@');
            let maskedEmail;
            
            if (localPart && localPart.length > 2) {
                maskedEmail = `${localPart.substring(0, 1)}***${localPart.substring(localPart.length - 1)}@${domain}`;
            } else {
                maskedEmail = `***@${domain || 'unknown.com'}`;
            }

            return {
                id: row.id,
                email: maskedEmail,
                status: row.status,
                date: row.created_at
            };
        });

        const activeCount = invites.filter(i => i.status === 'active').length;
        const subscribedCount = invites.filter(i => i.status === 'subscribed').length;

        res.json({
            referralCode,
            totalInvites: invites.length,
            activeCount,
            subscribedCount,
            invites
        });
    } catch (error) {
        console.error('Error fetching referral stats:', error);
        res.status(500).json({ message: 'Server error fetching referral stats' });
    }
};

exports.getAllReferrals = async (req, res) => {
    try {
        const statsRes = await db.query(`
            SELECT 
                r.id,
                r.status,
                r.created_at,
                r.reward_earned,
                u1.email as referrer_email,
                u1.name as referrer_name,
                u2.email as referee_email,
                u2.name as referee_name
            FROM referrals r
            JOIN users u1 ON r.referrer_id = u1.id
            JOIN users u2 ON r.referee_id = u2.id
            ORDER BY r.created_at DESC
        `);

        res.json(statsRes.rows);
    } catch (error) {
        console.error('Error fetching all referrals:', error);
        res.status(500).json({ message: 'Server error fetching referrals' });
    }
};

exports.getUserReferralDetails = async (req, res) => {
    try {
        const targetUserId = req.params.id;

        // Who referred them?
        const referredByRes = await db.query(`
            SELECT u.email, u.name, r.status, r.created_at
            FROM referrals r
            JOIN users u ON r.referrer_id = u.id
            WHERE r.referee_id = ?
        `, [targetUserId]);

        // Who did they refer?
        const invitedUsersRes = await db.query(`
            SELECT u.email, u.name, r.status, r.created_at
            FROM referrals r
            JOIN users u ON r.referee_id = u.id
            WHERE r.referrer_id = ?
        `, [targetUserId]);

        res.json({
            referredBy: referredByRes.rows[0] || null,
            invitedUsers: invitedUsersRes.rows
        });
    } catch (error) {
        console.error('Error fetching user referral details:', error);
        res.status(500).json({ message: 'Server error fetching user referral details' });
    }
};
