// Admin Organizations API Endpoints
const db = require('../db');

// ============================================
// GET ALL ORGANIZATIONS (Admin only)
// ============================================
const getAllOrganizations = async (req, res) => {
    try {
        const organizations = await db.query(
            `SELECT o.*,
                    u.name as owner_name, u.email as owner_email,
                    (SELECT COUNT(*) FROM organization_members WHERE organization_id = o.id) as member_count
             FROM organizations o
             LEFT JOIN users u ON o.owner_id = u.id
             ORDER BY o.created_at DESC`
        );
        
        // Calculate trial status for each org
        const orgsWithTrialInfo = organizations.rows.map(org => {
            let daysRemaining = null;
            let isTrial = org.plan_type === 'trial';
            
            if (org.trial_end_date) {
                const now = new Date();
                const endDate = new Date(org.trial_end_date);
                const diffTime = endDate - now;
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                daysRemaining = Math.max(0, diffDays);
                
                // If it's a trial plan, override status if expired
                if (isTrial && diffDays <= 0) {
                     // We don't update DB here to avoid read-side effects, but we report it
                }
            }

            return {
                ...org,
                days_remaining: daysRemaining
            };
        });

        res.json({ organizations: orgsWithTrialInfo });
    } catch (error) {
        console.error('Error fetching organizations:', error);
        res.status(500).json({ message: 'Failed to fetch organizations' });
    }
};

// ============================================
// UPDATE ORGANIZATION (Admin only)
// ============================================
const adminUpdateOrganization = async (req, res) => {
    try {
        const { id } = req.params;
        const { name, license_seats, plan_type, is_active } = req.body;
        
        await db.query(
            `UPDATE organizations SET name = ?, license_seats = ?, plan_type = ?, is_active = ?, updated_at = NOW() WHERE id = ?`,
            [name, license_seats, plan_type, is_active ? 1 : 0, id]
        );
        
        res.json({ message: 'Organization updated successfully' });
    } catch (error) {
        console.error('Error updating organization:', error);
        res.status(500).json({ message: 'Failed to update organization' });
    }
};

// ============================================
// DELETE ORGANIZATION (Admin only)
// ============================================
const deleteOrganization = async (req, res) => {
    try {
        const { id } = req.params;
        
        // Remove all members' org references
        await db.query('UPDATE users SET organization_id = NULL WHERE organization_id = ?', [id]);
        
        // Delete members
        await db.query('DELETE FROM organization_members WHERE organization_id = ?', [id]);
        
        // Delete invites
        await db.query('DELETE FROM organization_invites WHERE organization_id = ?', [id]);
        
        // Delete organization
        await db.query('DELETE FROM organizations WHERE id = ?', [id]);
        
        res.json({ message: 'Organization deleted successfully' });
    } catch (error) {
        console.error('Error deleting organization:', error);
        res.status(500).json({ message: 'Failed to delete organization' });
    }
};

// ============================================
// GET ORGANIZATION STATS (Admin only)
// ============================================
const getOrganizationStats = async (req, res) => {
    try {
        const { id } = req.params;
        
        const org = await db.query('SELECT * FROM organizations WHERE id = ?', [id]);
        
        if (org.rows.length === 0) {
            return res.status(404).json({ message: 'Organization not found' });
        }
        
        const members = await db.query(
            'SELECT user_id FROM organization_members WHERE organization_id = ?',
            [id]
        );
        const memberIds = members.rows.map(m => m.user_id);
        
        let stats = {
            totalXP: 0,
            totalInvestigations: 0,
            avgScore: 0
        };
        
        if (memberIds.length > 0) {
            const xpResult = await db.query(
                'SELECT SUM(total_xp) as total_xp FROM user_xp WHERE user_id IN (?)',
                [memberIds]
            );
            stats.totalXP = xpResult.rows[0]?.total_xp || 0;
            
            const invResult = await db.query(
                'SELECT COUNT(*) as total, AVG(grade) as avg_score FROM investigations WHERE user_id IN (?) AND status = "graded"',
                [memberIds]
            );
            stats.totalInvestigations = invResult.rows[0]?.total || 0;
            stats.avgScore = Math.round(invResult.rows[0]?.avg_score || 0);
        }
        
        res.json({
            organization: org.rows[0],
            stats
        });
    } catch (error) {
        console.error('Error fetching org stats:', error);
        res.status(500).json({ message: 'Failed to fetch stats' });
    }
};

module.exports = {
    getAllOrganizations,
    adminUpdateOrganization,
    deleteOrganization,
    getOrganizationStats
};
