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

const incidentTypeController = {
    // Get all incident types
    getAll: (req, res) => {
        IncidentType.findAll((err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json(results);
        });
    },

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

    // Create new incident type
    create: (req, res) => {
        const { name } = req.body;

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

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

            const existingType = results.find(type => 
                type.name.toLowerCase() === name.toLowerCase()
            );

            if (existingType) {
                return res.status(409).json({ 
                    error: 'Incident type with this name already exists',
                    message: `An incident type named "${name}" already exists.`
                });
            }

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

                // Fetch the created incident type to return it
                IncidentType.findById(results.insertId, (err, createdType) => {
                    if (err) {
                        return res.status(500).json({ error: err.message });
                    }
                    res.status(201).json({
                        message: 'Incident type created successfully',
                        incident_type: createdType[0]
                    });
                });
            });
        });
    },

    // Update incident type
    update: (req, res) => {
        const typeId = req.params.id;
        const { name } = req.body;

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

        // Check if incident type exists
        IncidentType.findById(typeId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'Incident type not found' });
            }

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

                const existingType = allTypes.find(type => 
                    type.id !== parseInt(typeId) && 
                    type.name.toLowerCase() === name.toLowerCase()
                );

                if (existingType) {
                    return res.status(409).json({ 
                        error: 'Incident type with this name already exists',
                        message: `An incident type named "${name}" already exists.`
                    });
                }

                // Update the incident type
                IncidentType.update(typeId, { name }, (err, updateResults) => {
                    if (err) {
                        return res.status(500).json({ error: err.message });
                    }

                    // Fetch the updated incident type to return it
                    IncidentType.findById(typeId, (err, updatedType) => {
                        if (err) {
                            return res.status(500).json({ error: err.message });
                        }
                        res.json({
                            message: 'Incident type updated successfully',
                            incident_type: updatedType[0]
                        });
                    });
                });
            });
        });
    },

    // Delete incident type
    delete: (req, res) => {
        const typeId = req.params.id;

        // Check if incident type exists
        IncidentType.findById(typeId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'Incident type not found' });
            }

            // Delete the incident type
            IncidentType.delete(typeId, (err, deleteResults) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }
                res.json({ 
                    message: 'Incident type deleted successfully',
                    deleted_incident_type: results[0]
                });
            });
        });
    }
};

module.exports = incidentTypeController;

