const IncidentDetails = require('../models/IncidentDetails');
const AmbulanceRequest = require('../models/AmbulanceRequest');

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

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

    // Get incident details by request ID
    getByRequestId: (req, res) => {
        const requestId = req.params.requestId;
        IncidentDetails.findByRequestId(requestId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'Incident details not found for this request' });
            }
            res.json(results[0]);
        });
    },

    // Create new incident details
    create: (req, res) => {
        const {
            request_id,
            number_of_casualties,
            is_member,
            bill_accepted,
            incident_type_id,
            incident_requirement_notes,
            general_notes
        } = req.body;

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

        // Check if request exists
        AmbulanceRequest.findRequestById(request_id, (err, requestResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (requestResults.length === 0) {
                return res.status(404).json({ 
                    error: 'Ambulance request not found',
                    message: `Request with ID ${request_id} does not exist`
                });
            }

            // Check if incident details already exist for this request
            IncidentDetails.findByRequestId(request_id, (err, existingDetails) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }
                if (existingDetails.length > 0) {
                    return res.status(409).json({ 
                        error: 'Incident details already exist for this request',
                        message: 'Each request can only have one incident details record'
                    });
                }

                // Create incident details
                IncidentDetails.create({
                    request_id,
                    number_of_casualties,
                    is_member,
                    bill_accepted,
                    incident_type_id,
                    incident_requirement_notes,
                    general_notes
                }, (err, results) => {
                    if (err) {
                        if (err.code === 'ER_DUP_ENTRY') {
                            return res.status(409).json({ 
                                error: 'Incident details already exist for this request'
                            });
                        }
                        if (err.code === 'ER_NO_REFERENCED_ROW_2') {
                            return res.status(400).json({ error: 'Invalid request_id or incident_type_id' });
                        }
                        return res.status(500).json({ error: err.message });
                    }

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

    // Update incident details
    update: (req, res) => {
        const detailsId = req.params.id;
        const {
            number_of_casualties,
            is_member,
            bill_accepted,
            incident_type_id,
            incident_requirement_notes,
            general_notes
        } = req.body;

        // Check if incident details exist
        IncidentDetails.findById(detailsId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'Incident details not found' });
            }

            // Update incident details
            IncidentDetails.update(detailsId, {
                number_of_casualties,
                is_member,
                bill_accepted,
                incident_type_id,
                incident_requirement_notes,
                general_notes
            }, (err, updateResults) => {
                if (err) {
                    if (err.code === 'ER_NO_REFERENCED_ROW_2') {
                        return res.status(400).json({ error: 'Invalid incident_type_id' });
                    }
                    return res.status(500).json({ error: err.message });
                }

                // Fetch the updated incident details to return it
                IncidentDetails.findById(detailsId, (err, updatedDetails) => {
                    if (err) {
                        return res.status(500).json({ error: err.message });
                    }
                    res.json({
                        message: 'Incident details updated successfully',
                        incident_details: updatedDetails[0]
                    });
                });
            });
        });
    },

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

        // Check if incident details exist
        IncidentDetails.findById(detailsId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'Incident details not found' });
            }

            // Delete incident details
            IncidentDetails.delete(detailsId, (err, deleteResults) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }
                res.json({ 
                    message: 'Incident details deleted successfully',
                    deleted_incident_details: results[0]
                });
            });
        });
    }
};

module.exports = incidentDetailsController;

