const express = require('express');
const router = express.Router();
const Certification = require('../models/Certification');

// Get certifications
router.get('/', async (req, res) => {
    try {
        const { category, level, page = 1, limit = 10 } = req.query;
        
        const filter = { isActive: true };
        if (category) filter.category = category;
        if (level) filter.level = level;
        
        const certifications = await Certification.find(filter)
            .sort({ name: 1 })
            .limit(limit * 1)
            .skip((page - 1) * limit);
            
        const total = await Certification.countDocuments(filter);
        
        res.status(200).json({
            success: true,
            data: {
                certifications,
                pagination: {
                    currentPage: parseInt(page),
                    totalPages: Math.ceil(total / limit),
                    totalCertifications: total,
                    hasNext: page < Math.ceil(total / limit),
                    hasPrev: page > 1
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Failed to get certifications',
            error: error.message
        });
    }
});

// Get certification details
router.get('/:certId', async (req, res) => {
    try {
        const certification = await Certification.findById(req.params.certId);
        
        if (!certification) {
            return res.status(404).json({
                success: false,
                message: 'Certification not found'
            });
        }
        
        res.status(200).json({
            success: true,
            data: certification
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Failed to get certification details',
            error: error.message
        });
    }
});

// Get certification categories
router.get('/categories', async (req, res) => {
    try {
        const categories = await Certification.aggregate([
            { $match: { isActive: true } },
            { $group: { _id: '$category', count: { $sum: 1 } } },
            { $sort: { count: -1 } }
        ]);
        
        const levels = await Certification.aggregate([
            { $match: { isActive: true } },
            { $group: { _id: '$level', count: { $sum: 1 } } },
            { $sort: { count: -1 } }
        ]);
        
        res.status(200).json({
            success: true,
            data: {
                categories,
                levels
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Failed to get certification categories',
            error: error.message
        });
    }
});

module.exports = router;
