const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const db = require('../db');
const { sendVerificationEmail, sendPasswordResetEmail } = require('../utils/emailService');
const xpService = require('../utils/xpService');
const { logEvent } = require('../utils/analytics');
const { formatUserUrls } = require('../utils/urlHelper');
const { isDisposableEmail } = require('../utils/disposableEmailChecker');

/**
 * Registers a new user or organization.
 * 
 * Capabilities:
 * - Validates password strength
 * - Checks for duplicate emails/usernames
 * - Auto-detects STUDENT status based on email domain (or whitelist)
 * - Creates Organization and starts Trial if 'organization' data is provided
 * - Sends Email Verification link
 * 
 * @route POST /api/auth/register
 * @access Public
 */
exports.register = async (req, res) => {
    const { name, password, username, surname, subscription_plan, organization, source } = req.body;
    let { email } = req.body;

    try {
        // 1. Email Normalization & Strict Validation
        if (!email || typeof email !== 'string') {
            return res.status(400).json({ message: 'Valid email is required.' });
        }
        
        email = email.toLowerCase().trim();

        // Stricter Email Regex (Prevents common typos like ..com, or trailing periods)
        const emailRegex = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
        if (!emailRegex.test(email)) {
            return res.status(400).json({ message: 'Invalid email format. Please check for typos (e.g. double dots).' });
        }

        // 1.5 Block Disposable/Temporary Email Providers
        if (isDisposableEmail(email)) {
            console.log(`[SECURITY] Blocked disposable email registration: ${email}`);
            return res.status(400).json({ message: 'Temporary or disposable email addresses are not allowed. Please use a permanent email address.' });
        }

        // 2. Input Validation
        if (!password || password.length < 8) {
            return res.status(400).json({ message: 'Password must be at least 8 characters long.' });
        }
        
        // Basic Password Strength Check
        const hasUpperCase = /[A-Z]/.test(password);
        const hasLowerCase = /[a-z]/.test(password);
        const hasNumbers = /\d/.test(password);
        const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);

        if (!hasUpperCase || !hasLowerCase || !hasNumbers || !hasSpecialChar) {
            return res.status(400).json({ message: 'Password must contain uppercase, lowercase, number, and special character.' });
        }

        // 3. Check if user exists (Email OR Username)
        const userCheck = await db.query('SELECT * FROM users WHERE email = ? OR username = ?', [email, username]);
        if (userCheck.rows.length > 0) {
            const existingUser = userCheck.rows[0];
            if (existingUser.email === email) {
                return res.status(400).json({ message: 'User already exists with this email' });
            }
            if (existingUser.username === username) {
                return res.status(400).json({ message: 'Username is already taken' });
            }
        }

        // Hash password
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        // Generate verification token
        const verificationToken = crypto.randomBytes(32).toString('hex');

        // Check for student domain
        const domain = email.split('@')[1];

        // Regex to match .edu or .edu.something at the end
        let isStudent = /\.edu(\.[a-z]{2,})?$/.test(email);
        
        if (!isStudent && domain) {
            const domainCheck = await db.query(
                'SELECT id FROM student_domains WHERE domain = ? OR domain = ?', 
                [domain, `@${domain}`]
            );
            if (domainCheck.rows.length > 0) {
                isStudent = true;
            }
        }

        // SECURITY: Check blocklist for fake/temp edu domains (usa.edu.pl, etc.)
        if (isStudent && domain) {
            try {
                const blockedCheck = await db.query(
                    'SELECT id FROM blocked_edu_domains WHERE domain = ?',
                    [domain]
                );
                if (blockedCheck.rows.length > 0) {
                    console.log(`[SECURITY] Blocked fake edu domain: ${domain}`);
                    isStudent = false; // Reject student status for blocked domains
                }
            } catch (blockErr) {
                // Table might not exist yet, ignore silently
                console.log('blocked_edu_domains table not found, skipping check');
            }
        }

        // 1. Process Incoming Referral Code (if any)
        let referredById = null;
        if (req.body.referralCode) {
            const refCheck = await db.query('SELECT id FROM users WHERE referral_code = ?', [req.body.referralCode]);
            if (refCheck.rows && refCheck.rows.length > 0) {
                referredById = refCheck.rows[0].id;
            }
        }

        // 2. Create User
        // SECURITY: Always force 'free' plan on register. Upgrades only via Stripe Webhook.
        const userResult = await db.query(
            'INSERT INTO users (name, email, password, username, surname, subscription_plan, role, is_verified, verification_token, is_student, registration_source, referred_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [name, email, hashedPassword, username, surname, 'free', 'normal', false, verificationToken, isStudent, source || 'web', referredById]
        );
        
        const newUserId = userResult.insertId;

        // 3. Generate structured User Referral Code and update
        const cleanName = (username || name || 'USER').replace(/[^A-Za-z0-9]/g, '').substring(0, 5).toUpperCase();
        const refStr = crypto.randomBytes(2).toString('hex').toUpperCase();
        const finalReferralCode = `${cleanName}-${newUserId}-${refStr}`;
        await db.query('UPDATE users SET referral_code = ? WHERE id = ?', [finalReferralCode, newUserId]);

        // 4. Create Pending Referral Row (if referred)
        if (referredById) {
            await db.query(`INSERT INTO referrals (referrer_id, referee_id, status) VALUES (?, ?, 'pending')`, [referredById, newUserId]);
        }

        // Log SIGNUP event
        await logEvent(newUserId, 'SIGNUP', { method: 'email', plan: 'free', is_student: isStudent, source: source || 'web' }, req);

        // HANDLE ORGANIZATION CREATION (If provided)
        if (organization) {
            const { name: orgName, team_size, position, industry, license_seats } = organization;
            
            if (orgName && orgName.trim().length >= 2) {
                // Generate slug
                let slug = orgName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
                const slugCheck = await db.query('SELECT id FROM organizations WHERE slug = ?', [slug]);
                if (slugCheck.rows.length > 0) {
                    slug = `${slug}-${Date.now().toString(36)}`;
                }

                // Trial dates
                const trialStartDate = new Date();
                const trialEndDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days

                // Create Org
                const orgResult = await db.query(
                    `INSERT INTO organizations (name, slug, owner_id, license_seats, used_seats, plan_type, team_size, admin_position, industry, trial_start_date, trial_end_date, trial_status) 
                     VALUES (?, ?, ?, ?, 1, 'trial', ?, ?, ?, ?, ?, 'active')`,
                    [orgName.trim(), slug, newUserId, license_seats || 5, team_size || '5-10', position || null, industry || null, trialStartDate, trialEndDate]
                );
                
                const orgId = orgResult.insertId;

                // Add owner as member
                await db.query(
                    `INSERT INTO organization_members (organization_id, user_id, role, joined_at) VALUES (?, ?, 'owner', NOW())`,
                    [orgId, newUserId]
                );

                // Update user's organization_id
                await db.query('UPDATE users SET organization_id = ? WHERE id = ?', [orgId, newUserId]);
            }
        }

        // Send verification email
        try {
            await sendVerificationEmail(email, verificationToken);
        } catch (emailError) {
            console.error('Failed to send verification email:', emailError);
        }

        // Auto-enroll free users in Alert Investigation path (ID 9) if NOT creating an org (Org owners might get different paths later)
        // Actually, let's just enroll everyone for now to be safe/consistent
        try {
            await db.query(
                'INSERT INTO user_path_progress (user_id, learning_path_id, percentage_completed) VALUES (?, 9, 0)',
                [newUserId]
            );
        } catch (enrollErr) {
            // Ignore if fails
        }

        // Auto-login: Generate session token and JWT so user can proceed to payment immediately
        const sessionToken = crypto.randomBytes(32).toString('hex');
        
        // Save session token (assuming web platform for registration)
        await db.query('UPDATE users SET session_token = ? WHERE id = ?', [sessionToken, newUserId]);

        const tokenPayload = { 
            id: newUserId, 
            sessionToken,
            type: 'web'
        };

        const token = jwt.sign(tokenPayload, process.env.JWT_SECRET, {
            expiresIn: '720h', 
        });

        res.status(201).json({
            message: 'Registration successful! Please check your email to verify your account.',
            token, // Return token for immediate payment flow
            user: {
                id: newUserId,
                name: name,
                email: email,
                username: username,
                role: 'normal',
                is_verified: false 
            }
        });
    } catch (error) {
        console.error('Registration Error:', error);
        res.status(500).json({ message: 'Server error: ' + (error.message || 'Unknown error') });
    }
};

/**
 * Authenticates a user.
 * 
 * Capabilities:
 * - Supports Login via Email or Username
 * - Checks for timed-out account locks (failed attempts)
 * - Verifies password hash
 * - Manages failed login attempts (lockout policy)
 * - Updates daily login streak
 * - Auto-upgrades to STUDENT status if needed
 * 
 * @route POST /api/auth/login
 * @access Public
 */
exports.login = async (req, res) => {
    const { email, username, password, identifier } = req.body;

    // Support email, username, or generic identifier field
    const loginIdentifier = identifier || email || username;

    if (!loginIdentifier || !password) {
        return res.status(400).json({ message: 'Please provide username/email and password' });
    }

    try {
        // Check for user by email or username
        // Check for user by email or username
        const result = await db.query('SELECT * FROM users WHERE email = ? OR username = ?', [loginIdentifier, loginIdentifier]);
        const user = result.rows[0];

        if (!user) {
            return res.status(400).json({ message: 'Invalid credentials' });
        }

        // Check if account is locked
        if (user.lock_until && new Date(user.lock_until) > new Date()) {
            const remainingTime = Math.ceil((new Date(user.lock_until) - new Date()) / (1000 * 60 * 60));
            return res.status(403).json({ message: `Account is locked. Please try again in ${remainingTime} hours.` });
        }

        // Check password
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            // Increment failed attempts
            const attempts = (user.failed_login_attempts || 0) + 1;

            if (attempts >= 3) {
                // Lock account for 1 hour
                const lockUntil = new Date(Date.now() + 60 * 60 * 1000);
                await db.query('UPDATE users SET failed_login_attempts = ?, lock_until = ? WHERE id = ?', [attempts, lockUntil, user.id]);

                // Send lockout email
                const { sendAccountLockedEmail } = require('../utils/emailService');
                await sendAccountLockedEmail(user.email, user.name);

                return res.status(403).json({ message: 'Account locked for 1 hour due to too many failed attempts.' });
            } else {
                await db.query('UPDATE users SET failed_login_attempts = ? WHERE id = ?', [attempts, user.id]);
                return res.status(400).json({ message: `Wrong password/username ${attempts}/3` });
            }
        }

        // Reset failed attempts on successful login
        if (user.failed_login_attempts > 0 || user.lock_until) {
            await db.query('UPDATE users SET failed_login_attempts = 0, lock_until = NULL WHERE id = ?', [user.id]);
        }

        // Update streak on login
        try {
            await xpService.updateStreak(user.id);
        } catch (streakError) {
            console.error('Error updating streak on login:', streakError);
        }

        // Check verification status
        if (!user.is_verified) {
            return res.status(403).json({ message: 'Account not verified. Please check your email.' });
        }

        // Generate unique session token for single-device enforcement
        const sessionToken = crypto.randomBytes(32).toString('hex');
        const platform = req.body.platform === 'mobile' ? 'mobile' : 'web';

        // Store session token in database based on platform
        if (platform === 'mobile') {
            await db.query('UPDATE users SET mobile_session_token = ? WHERE id = ?', [sessionToken, user.id]);
        } else {
            await db.query('UPDATE users SET session_token = ? WHERE id = ?', [sessionToken, user.id]);
        }

         // Log LOGIN event
         await logEvent(user.id, 'LOGIN', { method: 'credentials', role: user.role, platform }, req);

        // Create token with session token and platform type (if mobile) included
        // For web, we keep structure similar to before but verify differently
        const tokenPayload = { 
            id: user.id, 
            sessionToken,
            type: platform
        };

        const token = jwt.sign(tokenPayload, process.env.JWT_SECRET, {
            expiresIn: '720h', // 30 days for mobile/longer sessions, or keep 24h
        });

        res.json({
            token,
            user: formatUserUrls({
                id: user.id,
                name: user.name,
                email: user.email,
                username: user.username,
                role: user.role,
                profile_picture: user.profile_picture,
                created_at: user.created_at,
                training_completed: await checkTrainingStatus(user),
                current_mission: user.current_mission,
                badges: (() => {
                    try {
                        return typeof user.badges === 'string' ? JSON.parse(user.badges) : (user.badges || []);
                    } catch (e) {
                        return [];
                    }
                })()
            })
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error check log' });
    }
};

// Helper: Check if training is enforced
const checkTrainingStatus = async (user) => {
    if (user.training_completed) return true;

    // Check global setting
    const setting = await db.query("SELECT value FROM system_settings WHERE `key` = 'training_enabled'");
    // If setting exists and is 'false', return true (completed) to bypass.
    // Default to true (enabled) if missing.
    if (setting.rows.length > 0) {
        const val = setting.rows[0].value;
        if (val === 'false' || val === false || val === '"false"') return true;
    }
    return false;
};

exports.verifyEmail = async (req, res) => {
    const { token } = req.params;

    try {
        const result = await db.query('SELECT * FROM users WHERE verification_token = ?', [token]);
        const user = result.rows[0];

        if (!user) {
            return res.status(400).json({ message: 'Invalid or expired verification token' });
        }

        await db.query('UPDATE users SET is_verified = TRUE, verification_token = NULL WHERE id = ?', [user.id]);

        res.json({ message: 'Email verified successfully. You can now login.' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.forgotPassword = async (req, res) => {
    const { email } = req.body;

    try {
        const result = await db.query('SELECT * FROM users WHERE email = ?', [email]);
        const user = result.rows[0];

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

        const resetToken = crypto.randomBytes(32).toString('hex');
        const resetExpires = new Date(Date.now() + 3600000); // 1 hour

        await db.query('UPDATE users SET reset_password_token = ?, reset_password_expires = ? WHERE id = ?', [resetToken, resetExpires, user.id]);

        await sendPasswordResetEmail(email, resetToken);

        res.json({ message: 'Password reset email sent' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.resetPassword = async (req, res) => {
    const { token } = req.params;
    const { password } = req.body;

    try {
        const result = await db.query('SELECT * FROM users WHERE reset_password_token = ? AND reset_password_expires > NOW()', [token]);
        const user = result.rows[0];

        if (!user) {
            return res.status(400).json({ message: 'Invalid or expired reset token' });
        }

        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        await db.query('UPDATE users SET password = ?, reset_password_token = NULL, reset_password_expires = NULL, lock_until = NULL, failed_login_attempts = 0 WHERE id = ?', [hashedPassword, user.id]);

        res.json({ message: 'Password reset successfully' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.getAllUsers = async (req, res) => {
    try {
        const result = await db.query(`
            SELECT 
                u.id, u.name, u.email, u.username, u.role, u.is_student, u.created_at, u.subscription_plan, u.is_verified,
                u.subscription_status, u.cancel_at_period_end, u.lock_until, u.failed_login_attempts,
                COALESCE(u.renewal_date, u.subscription_end_date) as renewal_date,
                u.registration_source,
                u.badges as legacy_badges,
                om.organization_id,
                o.name as organization_name,
                om.role as org_role,
                (SELECT COUNT(*) FROM alerts a WHERE a.assigned_to = u.id) as assigned_count,
                (SELECT COUNT(*) FROM investigations i WHERE i.user_id = u.id) as investigated_count,
                (
                    SELECT JSON_ARRAYAGG(JSON_OBJECT('name', b.name, 'icon', b.icon_url, 'description', b.description))
                    FROM user_badges ub
                    JOIN badges b ON ub.badge_id = b.id
                    WHERE ub.user_id = u.id
                ) as earned_badges
            FROM users u 
            LEFT JOIN organization_members om ON u.id = om.user_id
            LEFT JOIN organizations o ON om.organization_id = o.id
            ORDER BY u.created_at DESC
        `);
        res.json(result.rows);
    } catch (error) {
        console.error("Error fetching users:", error);
        res.status(500).json({ message: `Server error fetching users: ${error.message}` });
    }
};

exports.updateUserRole = async (req, res) => {
    const { id } = req.params;
    const { role, subscription_plan, is_student } = req.body;

    try {
        if (role) {
            await db.query('UPDATE users SET role = ? WHERE id = ?', [role, id]);
        }
        if (subscription_plan) {
            await db.query('UPDATE users SET subscription_plan = ? WHERE id = ?', [subscription_plan, id]);
        }
        if (is_student !== undefined) {
             await db.query('UPDATE users SET is_student = ? WHERE id = ?', [is_student, id]);
        }

        const result = await db.query('SELECT id, role, subscription_plan FROM users WHERE id = ?', [id]);
        if (result.rows.length === 0) {
            return res.status(404).json({ message: 'User not found' });
        }
        res.json(result.rows[0]);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
};

/**
 * Retrieves the current user regarding the session.
 * 
 * Capabilities:
 * - Fetches user profile, role, and subscription status
 * - Checks robustly for Student Whitelist status (@domain or domain)
 * - Updates user streak (Daily Login)
 * - Persists 'is_student' status to DB if found in whitelist interactively
 * 
 * @route GET /api/auth/me
 * @access Private
 */
exports.getMe = async (req, res) => {
    try {
        const userResult = await db.query('SELECT id, name, surname, email, username, role, profile_picture, is_student, subscription_plan, subscription_end_date, badges, current_mission, training_completed, created_at FROM users WHERE id = ?', [req.user.id]);
        const user = userResult.rows[0];

        // Check Whitelisted Domains if not already identified
        if (!user.is_student) {
            const domain = user.email.split('@')[1];
            if (domain) {
                // Check robustly: exact domain OR @domain
                const domainCheck = await db.query(
                    'SELECT 1 FROM student_domains WHERE domain = ? OR domain = ?', 
                    [domain.toLowerCase(), `@${domain.toLowerCase()}`]
                );
                if (domainCheck.rows.length > 0) {
                    user.is_student = true; 
                    // Persist to DB so they show up in Admin lists
                    await db.query('UPDATE users SET is_student = TRUE WHERE id = ?', [user.id]);
                }
            }
        }

        // Update streak on session check (getMe)
        // This ensures streak is maintained even if user doesn't logout/login but just visits the site
        try {
            await xpService.updateStreak(req.user.id);
        } catch (streakError) {
            console.error('Error updating streak on getMe:', streakError);
        }

        // Parse badges if string
        try {
            if (typeof user.badges === 'string') {
                user.badges = JSON.parse(user.badges);
            }
        } catch (e) {
            user.badges = [];
        }

        // Apply override logic
        user.training_completed = await checkTrainingStatus(user);

        res.json(formatUserUrls(user));
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.deleteAccount = async (req, res) => {
    const userId = req.user.id;
    try {
        // Option 1: Hard Delete (simplest for now, ensures compliance)
        // Check constraints: user_badges, alerts, investigations, user_path_progress
        // Ideally we should soft delete or anonymize, but hard delete is what user expects.
        
        // Delete dependent records first (if foreign keys don't have ON DELETE CASCADE)
        // Note: In many simple schemas, we might rely on CASCADE or manual cleanup.
        // Let's safe delete known dependencies.
        await db.query('DELETE FROM user_badges WHERE user_id = ?', [userId]);
        await db.query('DELETE FROM user_path_progress WHERE user_id = ?', [userId]);
        await db.query('DELETE FROM user_operation_progress WHERE user_id = ?', [userId]);
        await db.query('DELETE FROM investigations WHERE user_id = ?', [userId]); // Or set null? Delete is cleaner for user
        
        // Alerts assigned to user: Set to null to preserve alert history but remove assignment
        await db.query('UPDATE alerts SET assigned_to = NULL WHERE assigned_to = ?', [userId]);

        // Finally delete User
        await db.query('DELETE FROM users WHERE id = ?', [userId]);

        res.json({ message: 'Account deleted successfully' });
    } catch (error) {
        console.error('Delete Account Error:', error);
        res.status(500).json({ message: 'Failed to delete account' });
    }
};

exports.checkAvailability = async (req, res) => {
    const { field, value } = req.body;

    if (!value || value.length < 3) {
         return res.json({ available: false, message: 'Too short' });
    }

    try {
        if (field === 'username') {
            const result = await db.query('SELECT id FROM users WHERE username = ?', [value]);
            if (result.rows.length > 0) {
                return res.json({ available: false, message: 'Username is taken' });
            } else {
                return res.json({ available: true, message: 'Username is available' });
            }
        } else if (field === 'email') {
             const result = await db.query('SELECT id FROM users WHERE email = ?', [value]);
             if (result.rows.length > 0) {
                 return res.json({ available: false, message: 'Email is already registered' });
             } else {
                 return res.json({ available: true, message: 'Email is available' });
             }
        } else {
            return res.status(400).json({ message: 'Invalid field' });
        }
    } catch (error) {
        console.error('Check Availability Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.changePassword = async (req, res) => {
    const { currentPassword, newPassword } = req.body;
    const userId = req.user.id;

    try {
        // 1. Get user from DB
        const result = await db.query('SELECT password FROM users WHERE id = ?', [userId]);
        const user = result.rows[0];

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

        // 2. Check current password
        const isMatch = await bcrypt.compare(currentPassword, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Current password is incorrect' });
        }

        // 3. Validate new password strength
        if (!newPassword || newPassword.length < 8) {
            return res.status(400).json({ message: 'New password must be at least 8 characters long.' });
        }

        const hasUpperCase = /[A-Z]/.test(newPassword);
        const hasLowerCase = /[a-z]/.test(newPassword);
        const hasNumbers = /\d/.test(newPassword);
        const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(newPassword);

        if (!hasUpperCase || !hasLowerCase || !hasNumbers || !hasSpecialChar) {
            return res.status(400).json({ message: 'New password must contain uppercase, lowercase, number, and special character.' });
        }

        // 4. Hash new password
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(newPassword, salt);

        // 5. Update password
        await db.query('UPDATE users SET password = ? WHERE id = ?', [hashedPassword, userId]);

        res.json({ message: 'Password updated successfully' });
    } catch (error) {
        console.error('Change Password Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

// Check if a domain/email is eligible for student status
exports.checkStudentDomain = async (req, res) => {
    try {
        const { email } = req.body;
        if (!email) return res.status(400).json({ message: 'Email required' });

        // Check for student domain (supports .edu and .edu.xx like .edu.tr, .edu.sa)
        const normalizedEmail = email.toLowerCase().trim();
        const domain = normalizedEmail.split('@')[1];
        
        // Regex to match .edu or .edu.something at the end
        let isStudent = /\.edu(\.[a-z]{2,})?$/.test(normalizedEmail);
        
        if (!isStudent && domain) {
            // Check robustly: exact domain OR @domain (just in case)
            const domainCheck = await db.query(
                'SELECT id FROM student_domains WHERE domain = ? OR domain = ?', 
                [domain, `@${domain}`]
            );
            if (domainCheck.rows.length > 0) {
                isStudent = true;
            }
        }

        // SECURITY: Check blocklist for fake/temp edu domains
        if (isStudent && domain) {
            try {
                const blockedCheck = await db.query(
                    'SELECT id FROM blocked_edu_domains WHERE domain = ?',
                    [domain]
                );
                if (blockedCheck.rows.length > 0) {
                    isStudent = false; // Reject student status for blocked domains
                }
            } catch (blockErr) {
                // Table might not exist yet, ignore
            }
        }

        res.json({ is_student: isStudent });
    } catch (error) {
        console.error('Error checking student domain:', error);
        res.status(500).json({ message: 'Server error' });
    }
};
