const MasmScheme = require('../models/MasmScheme');

const masmSchemeController = {
    // Get all MASM schemes
    getAll: (req, res) => {
        MasmScheme.findAll((err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json(results);
        });
    },

    // Get MASM scheme by ID
    getById: (req, res) => {
        const schemeId = req.params.id;
        MasmScheme.findById(schemeId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'MASM scheme not found' });
            }
            res.json(results[0]);
        });
    },

    // Create new MASM scheme
    create: (req, res) => {
        const { name, desc } = req.body;

        // Validate required fields
        if (!name) {
            return res.status(400).json({ 
                error: 'Missing required field: name is required' 
            });
        }

        // Check if scheme with same name already exists
        MasmScheme.findAll((err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }

            const existingScheme = results.find(scheme => 
                scheme.name.toLowerCase() === name.toLowerCase()
            );

            if (existingScheme) {
                return res.status(409).json({ 
                    error: 'MASM scheme with this name already exists',
                    message: `A scheme named "${name}" already exists.`
                });
            }

            // Create the scheme
            MasmScheme.create({ name, desc }, (err, results) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }

                // Fetch the created scheme to return it
                MasmScheme.findById(results.insertId, (err, createdScheme) => {
                    if (err) {
                        return res.status(500).json({ error: err.message });
                    }
                    res.status(201).json({
                        message: 'MASM scheme created successfully',
                        scheme: createdScheme[0]
                    });
                });
            });
        });
    },

    // Update MASM scheme
    update: (req, res) => {
        const schemeId = req.params.id;
        const { name, desc } = req.body;

        // Validate required fields
        if (!name) {
            return res.status(400).json({ 
                error: 'Missing required field: name is required' 
            });
        }

        // Check if scheme exists
        MasmScheme.findById(schemeId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'MASM scheme not found' });
            }

            // Check if another scheme with the same name exists (excluding current scheme)
            MasmScheme.findAll((err, allSchemes) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }

                const existingScheme = allSchemes.find(scheme => 
                    scheme.id !== parseInt(schemeId) && 
                    scheme.name.toLowerCase() === name.toLowerCase()
                );

                if (existingScheme) {
                    return res.status(409).json({ 
                        error: 'MASM scheme with this name already exists',
                        message: `A scheme named "${name}" already exists.`
                    });
                }

                // Update the scheme
                MasmScheme.update(schemeId, { name, desc }, (err, updateResults) => {
                    if (err) {
                        return res.status(500).json({ error: err.message });
                    }

                    // Fetch the updated scheme to return it
                    MasmScheme.findById(schemeId, (err, updatedScheme) => {
                        if (err) {
                            return res.status(500).json({ error: err.message });
                        }
                        res.json({
                            message: 'MASM scheme updated successfully',
                            scheme: updatedScheme[0]
                        });
                    });
                });
            });
        });
    },

    // Delete MASM scheme
    delete: (req, res) => {
        const schemeId = req.params.id;

        // Check if scheme exists
        MasmScheme.findById(schemeId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'MASM scheme not found' });
            }

            // Delete the scheme
            MasmScheme.delete(schemeId, (err, deleteResults) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }
                res.json({ 
                    message: 'MASM scheme deleted successfully',
                    deleted_scheme: results[0]
                });
            });
        });
    }
};

module.exports = masmSchemeController;



