const db = require('../config/database');

const Dispatch = {
    // Create new dispatch
    create: (dispatchData, callback) => {
        const { ambulance_request_id, ambulance_id, driver_id } = dispatchData;
        const query = 
            `INSERT INTO dispatch (ambulance_request_id, ambulance_id, driver_id) 
            VALUES (?, ?, ?)`;
        
        db.query(query, [ambulance_request_id, ambulance_id, driver_id], callback);
    },

    // Find dispatch by request ID
    findByRequestId: (requestId, callback) => {
        const query = 'SELECT * FROM dispatch WHERE ambulance_request_id = ?';
        db.query(query, [requestId], callback);
    },

    // Find dispatch by ID
    findById: (dispatchId, callback) => {
        const query = 'SELECT * FROM dispatch WHERE id = ?';
        db.query(query, [dispatchId], callback);
    },

    // Get all dispatches with related data
    findAll: (callback) => {
        const query = 
            `SELECT 
                d.*,
                ar.id as request_id,
                ar.location,
                ar.destination,
                ar.status as request_status,
                a.vehicle_number,
                a.license_plate,
                dr.license_number as driver_license
            FROM dispatch d
            INNER JOIN ambulance_requests ar ON d.ambulance_request_id = ar.id
            INNER JOIN ambulance a ON d.ambulance_id = a.id
            INNER JOIN driver dr ON d.driver_id = dr.id
            ORDER BY d.id DESC`;
        db.query(query, callback);
    },

    // Delete dispatch by request ID
    deleteByRequestId: (requestId, callback) => {
        const query = 'DELETE FROM dispatch WHERE ambulance_request_id = ?';
        db.query(query, [requestId], callback);
    },

    // Delete dispatch by ID
    delete: (dispatchId, callback) => {
        const query = 'DELETE FROM dispatch WHERE id = ?';
        db.query(query, [dispatchId], callback);
    }
};

module.exports = Dispatch;

