const Driver = require('../models/Driver');
const AmbulanceRequest = require('../models/AmbulanceRequest');
const Dispatch = require('../models/Dispatch');
const Notification = require('../models/Notification');
const User = require('../models/User');
const { sendPushToUser } = require('../config/push');
const bcrypt = require('bcryptjs');

const createNotificationRecord = (userId, text, requestId = null) =>
    new Promise((resolve) => {
        if (!userId || !text) {
            return resolve(null);
        }
        Notification.create({ user_id: userId, request_id: requestId, text }, (err, result) => {
            if (err) {
                console.error('Failed to persist notification:', err.message);
                return resolve({ error: err.message });
            }
            resolve({ id: result.insertId, user_id: userId, request_id: requestId, text });
        });
    });

const driverController = {
    // Get all drivers
    getAll: (req, res) => {
        Driver.findAll((err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json(results);
        });
    },

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

    // Get driver by user ID
    getByUserId: (req, res) => {
        const userId = req.params.userId;
        Driver.findByUserId(userId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'Driver not found' });
            }
            res.json(results[0]);
        });
    },

    // Get drivers by status
    getByStatus: (req, res) => {
        const status = req.params.status;
        Driver.findByStatus(status, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json(results);
        });
    },

    // Get drivers by ambulance ID
    getByAmbulanceId: (req, res) => {
        const ambulanceId = req.params.ambulanceId;
        Driver.findByAmbulanceId(ambulanceId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json(results);
        });
    },

    // Create new driver with user (creates both user and driver records)
    createWithUser: (req, res) => {
        const { 
            first_name, 
            last_name, 
            email, 
            license_number, 
            ambulance_id, 
            status 
        } = req.body;
        
        const DEFAULT_PASSWORD = '123456789';
        
        // Validate required fields
        if (!first_name || !last_name || !email || !license_number) {
            return res.status(400).json({ 
                error: 'Missing required fields: first_name, last_name, email, and license_number are required' 
            });
        }

        // Check if email already exists
        User.findByEmail(email, (err, emailResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            
            if (emailResults.length > 0) {
                return res.status(400).json({ error: 'Email already registered' });
            }

            // Hash the password
            bcrypt.hash(DEFAULT_PASSWORD, 10, (err, hashedPassword) => {
                if (err) {
                    return res.status(500).json({ error: 'Error hashing password' });
                }

                // Create user first
                User.create({
                    first_name,
                    last_name,
                    email,
                    password: hashedPassword,
                    role: 'driver',
                    otp: null,
                    is_verified: true  // Auto-verify driver accounts
                }, (err, userResults) => {
                    if (err) {
                        if (err.code === 'ER_DUP_ENTRY') {
                            return res.status(400).json({ error: 'Email already exists' });
                        }
                        return res.status(500).json({ error: err.message });
                    }

                    const userId = userResults.insertId;

                    // Create driver record
                    Driver.create({
                        user_id: userId,
                        license_number,
                        ambulance_id,
                        status
                    }, (err, driverResults) => {
                        if (err) {
                            // Rollback: delete user if driver creation fails
                            User.delete(userId, () => {});
                            
                            if (err.code === 'ER_DUP_ENTRY') {
                                return res.status(400).json({ error: 'License number already exists' });
                            }
                            if (err.code === 'ER_NO_REFERENCED_ROW_2') {
                                return res.status(400).json({ error: 'Invalid ambulance ID' });
                            }
                            return res.status(500).json({ error: err.message });
                        }

                        // Get the created driver with user info
                        Driver.findById(driverResults.insertId, (err, driverData) => {
                            if (err) {
                                return res.status(500).json({ error: err.message });
                            }

                            res.status(201).json({
                                message: 'Driver and user created successfully',
                                driver: driverData[0],
                                user: {
                                    id: userId,
                                    first_name,
                                    last_name,
                                    email,
                                    role: 'driver',
                                    is_verified: true
                                },
                                note: 'Default password is: 123456789'
                            });
                        });
                    });
                });
            });
        });
    },

    // Create new driver (existing - requires user_id)
    create: (req, res) => {
        const { user_id, license_number, ambulance_id, status } = req.body;
        
        if (!user_id || !license_number) {
            return res.status(400).json({ error: 'User ID and license number are required' });
        }

        Driver.create({
            user_id,
            license_number,
            ambulance_id,
            status
        }, (err, results) => {
            if (err) {
                // Check for duplicate entry error
                if (err.code === 'ER_DUP_ENTRY') {
                    return res.status(400).json({ error: 'User already has a driver record or license number already exists' });
                }
                // Check for foreign key constraint error
                if (err.code === 'ER_NO_REFERENCED_ROW_2') {
                    return res.status(400).json({ error: 'Invalid user ID or ambulance ID' });
                }
                return res.status(500).json({ error: err.message });
            }
            res.status(201).json({ 
                message: 'Driver created successfully', 
                id: results.insertId 
            });
        });
    },

    // Update driver
    update: (req, res) => {
        const driverId = req.params.id;
        const { license_number, ambulance_id, status } = req.body;
        
        if (!license_number) {
            return res.status(400).json({ error: 'License number is required' });
        }

        Driver.update(driverId, {
            license_number,
            ambulance_id,
            status
        }, (err, results) => {
            if (err) {
                // Check for duplicate entry error
                if (err.code === 'ER_DUP_ENTRY') {
                    return res.status(400).json({ error: 'License number already exists' });
                }
                // Check for foreign key constraint error
                if (err.code === 'ER_NO_REFERENCED_ROW_2') {
                    return res.status(400).json({ error: 'Invalid ambulance ID' });
                }
                return res.status(500).json({ error: err.message });
            }
            if (results.affectedRows === 0) {
                return res.status(404).json({ message: 'Driver not found' });
            }
            res.json({ message: 'Driver updated successfully' });
        });
    },

    // Update driver status
    updateStatus: (req, res) => {
        const driverId = req.params.id;
        const { status } = req.body;
        
        if (!status) {
            return res.status(400).json({ error: 'Status is required' });
        }

        Driver.updateStatus(driverId, status, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.affectedRows === 0) {
                return res.status(404).json({ message: 'Driver not found' });
            }
            res.json({ message: 'Driver status updated successfully' });
        });
    },

    // Assign driver to ambulance
    assignAmbulance: (req, res) => {
        const driverId = req.params.id;
        const { ambulance_id } = req.body;
        
        if (ambulance_id === undefined) {
            return res.status(400).json({ error: 'Ambulance ID is required' });
        }

        Driver.assignAmbulance(driverId, ambulance_id, (err, results) => {
            if (err) {
                // Check for foreign key constraint error
                if (err.code === 'ER_NO_REFERENCED_ROW_2') {
                    return res.status(400).json({ error: 'Invalid ambulance ID' });
                }
                return res.status(500).json({ error: err.message });
            }
            if (results.affectedRows === 0) {
                return res.status(404).json({ message: 'Driver not found' });
            }
            res.json({ message: 'Driver assigned to ambulance successfully' });
        });
    },

    // Unassign driver from ambulance
    unassignAmbulance: (req, res) => {
        const driverId = req.params.id;
        Driver.unassignAmbulance(driverId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.affectedRows === 0) {
                return res.status(404).json({ message: 'Driver not found' });
            }
            res.json({ message: 'Driver unassigned from ambulance successfully' });
        });
    },

    // Delete driver
    delete: (req, res) => {
        const driverId = req.params.id;
        Driver.delete(driverId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.affectedRows === 0) {
                return res.status(404).json({ message: 'Driver not found' });
            }
            res.json({ message: 'Driver deleted successfully' });
        });
    },

    // Get authenticated driver details with assigned ambulance
    getMyProfile: (req, res) => {
        const userId = req.user?.id;

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }

        Driver.findDetailedByUserId(userId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (!results.length) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const profile = results[0];
            const ambulance = profile.ambulance_id
                ? {
                    id: profile.ambulance_id,
                    vehicle_number: profile.vehicle_number,
                    license_plate: profile.license_plate,
                    model: profile.model,
                    make: profile.make,
                    status: profile.ambulance_status,
                    created_at: profile.ambulance_created_at,
                    updated_at: profile.ambulance_updated_at
                }
                : null;

            res.json({
                driver: {
                    id: profile.driver_id,
                    user_id: profile.user_id,
                    license_number: profile.license_number,
                    ambulance_id: profile.assigned_ambulance_id,
                    status: profile.driver_status,
                    created_at: profile.driver_created_at,
                    updated_at: profile.driver_updated_at
                },
                user: {
                    first_name: profile.first_name,
                    last_name: profile.last_name,
                    email: profile.email,
                    phone_number: profile.phone_number,
                    role: profile.role,
                    is_verified: profile.is_verified
                },
                ambulance
            });
        });
    },

    // Partially update authenticated driver's profile/user fields
    updateMyProfile: (req, res) => {
        const userId = req.user?.id;
        const { phone_number, license_number, ambulance_id, status } = req.body || {};

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }

        if (
            phone_number === undefined &&
            license_number === undefined &&
            ambulance_id === undefined &&
            status === undefined
        ) {
            return res.status(400).json({ error: 'No fields provided to update' });
        }

        Driver.findByUserId(userId, (driverErr, driverResults) => {
            if (driverErr) {
                return res.status(500).json({ error: driverErr.message });
            }
            if (driverResults.length === 0) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const updateTasks = [];

            if (phone_number !== undefined) {
                updateTasks.push(
                    new Promise((resolve, reject) => {
                        const User = require('../models/User');
                        User.update(userId, { phone_number }, (err, results) => {
                            if (err) {
                                return reject(err);
                            }
                            resolve(results);
                        });
                    })
                );
            }

            if (license_number !== undefined || ambulance_id !== undefined || status !== undefined) {
                updateTasks.push(
                    new Promise((resolve, reject) => {
                        Driver.updateByUserIdPartial(
                            userId,
                            { license_number, ambulance_id, status },
                            (err, results) => {
                                if (err) {
                                    return reject(err);
                                }
                                resolve(results);
                            }
                        );
                    })
                );
            }

            Promise.all(updateTasks)
                .then(() => {
                    Driver.findDetailedByUserId(userId, (detailErr, detailResults) => {
                        if (detailErr) {
                            return res.status(500).json({ error: detailErr.message });
                        }
                        if (!detailResults.length) {
                            return res.status(404).json({ message: 'Driver profile not found after update' });
                        }

                        const profile = detailResults[0];
                        const ambulance = profile.ambulance_id
                            ? {
                                id: profile.ambulance_id,
                                vehicle_number: profile.vehicle_number,
                                license_plate: profile.license_plate,
                                model: profile.model,
                                make: profile.make,
                                status: profile.ambulance_status,
                                created_at: profile.ambulance_created_at,
                                updated_at: profile.ambulance_updated_at
                            }
                            : null;

                        res.json({
                            driver: {
                                id: profile.driver_id,
                                user_id: profile.user_id,
                                license_number: profile.license_number,
                                ambulance_id: profile.assigned_ambulance_id,
                                status: profile.driver_status,
                                created_at: profile.driver_created_at,
                                updated_at: profile.driver_updated_at
                            },
                            user: {
                                first_name: profile.first_name,
                                last_name: profile.last_name,
                                email: profile.email,
                                phone_number: profile.phone_number,
                                role: profile.role,
                                is_verified: profile.is_verified
                            },
                            ambulance
                        });
                    });
                })
                .catch((updateErr) => {
                    // Handle specific errors (e.g., duplicate license)
                    if (updateErr.code === 'ER_DUP_ENTRY') {
                        return res.status(400).json({ error: 'License number already exists' });
                    }
                    if (updateErr.message === 'No fields to update') {
                        return res.status(400).json({ error: 'No fields provided to update' });
                    }
                    return res.status(500).json({ error: updateErr.message });
                });
        });
    },

    // Get the latest active request assigned to the authenticated driver
    getMyActiveRequests: (req, res) => {
        const userId = req.user?.id;

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }

        Driver.findByUserId(userId, (err, driverResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (driverResults.length === 0) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const driverId = driverResults[0].id;
            AmbulanceRequest.findActiveByDriverId(driverId, (requestErr, requests) => {
                if (requestErr) {
                    return res.status(500).json({ error: requestErr.message });
                }
                if (!requests.length) {
                    return res.status(404).json({ message: 'No active requests assigned to this driver' });
                }
                res.json(requests[0]);
            });
        });
    },

    // Get recent requests assigned to the authenticated driver
    getMyRecentRequests: (req, res) => {
        const userId = req.user?.id;
        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }

        const limit = 5;

        Driver.findByUserId(userId, (err, driverResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (driverResults.length === 0) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const driverId = driverResults[0].id;
            AmbulanceRequest.findRecentByDriverId(driverId, limit, (requestErr, requests) => {
                if (requestErr) {
                    return res.status(500).json({ error: requestErr.message });
                }
                res.json(requests);
            });
        });
    },

    // Get all requests/trips assigned to the authenticated driver
    getMyTrips: (req, res) => {
        const userId = req.user?.id;
        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }

        Driver.findByUserId(userId, (err, driverResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (driverResults.length === 0) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const driverId = driverResults[0].id;
            AmbulanceRequest.findAllByDriverId(driverId, (requestErr, requests) => {
                if (requestErr) {
                    return res.status(500).json({ error: requestErr.message });
                }
                res.json(requests);
            });
        });
    },

    // Get aggregate trip stats for the authenticated driver
    getMyTripStats: (req, res) => {
        const userId = req.user?.id;
        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }

        Driver.findByUserId(userId, (err, driverResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (driverResults.length === 0) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const driverId = driverResults[0].id;
            AmbulanceRequest.getDriverTripStats(driverId, (statsErr, statsRows) => {
                if (statsErr) {
                    return res.status(500).json({ error: statsErr.message });
                }

                const stats = statsRows && statsRows[0] ? statsRows[0] : {};
                const tripsToday = Number(stats.trips_today) || 0;
                const totalTrips = Number(stats.total_trips) || 0;
                const avgResponseSeconds =
                    stats.avg_response_seconds === null || stats.avg_response_seconds === undefined
                        ? null
                        : Number(stats.avg_response_seconds);

                return res.json({
                    trips_today: tripsToday,
                    total_trips: totalTrips,
                    avg_response_time_seconds: avgResponseSeconds,
                });
            });
        });
    },

    // Confirm pickup (sets pickup_confirmed_at) for a driver's trip
    confirmPickup: (req, res) => {
        const userId = req.user?.id;
        const requestId = req.params.requestId || req.body.request_id;

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }
        if (!requestId) {
            return res.status(400).json({ error: 'requestId is required' });
        }

        Driver.findByUserId(userId, (err, driverResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (driverResults.length === 0) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const driverId = driverResults[0].id;
            AmbulanceRequest.findAllByDriverId(driverId, (requestErr, requests) => {
                if (requestErr) {
                    return res.status(500).json({ error: requestErr.message });
                }

                const ownsRequest = requests.some((r) => {
                    const reqId = r.request_id || r.id;
                    return Number(reqId) === Number(requestId);
                });
                if (!ownsRequest) {
                    return res.status(403).json({ error: 'Trip does not belong to this driver' });
                }

                AmbulanceRequest.markPickupConfirmed(requestId, (updateErr) => {
                    if (updateErr) {
                        return res.status(500).json({ error: updateErr.message });
                    }

                    return res.json({ message: 'Pickup confirmed' });
                });
            });
        });
    },

    // Start trip (sets trip_started_at without changing status)
    startTrip: (req, res) => {
        const userId = req.user?.id;
        const requestId = req.params.requestId || req.body.request_id;

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }
        if (!requestId) {
            return res.status(400).json({ error: 'requestId is required' });
        }

        Driver.findByUserId(userId, (err, driverResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (driverResults.length === 0) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const driverId = driverResults[0].id;
            AmbulanceRequest.findAllByDriverId(driverId, (requestErr, requests) => {
                if (requestErr) {
                    return res.status(500).json({ error: requestErr.message });
                }

                const ownsRequest = requests.some((r) => {
                    const reqId = r.request_id || r.id;
                    return Number(reqId) === Number(requestId);
                });
                if (!ownsRequest) {
                    return res.status(403).json({ error: 'Trip does not belong to this driver' });
                }

                AmbulanceRequest.markTripStarted(requestId, (updateErr) => {
                    if (updateErr) {
                        return res.status(500).json({ error: updateErr.message });
                    }

                    return res.json({ message: 'Trip started' });
                });
            });
        });
    },

    // Self-assign a pending request
    selfAssignRequest: (req, res) => {
        const userId = req.user?.id;
        const requestId = req.params.requestId || req.body.request_id;

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized. User context missing.' });
        }
        if (!requestId) {
            return res.status(400).json({ error: 'requestId is required' });
        }

        // Get driver information
        Driver.findByUserId(userId, (err, driverResults) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (driverResults.length === 0) {
                return res.status(404).json({ message: 'Driver profile not found for this user' });
            }

            const driver = driverResults[0];
            const driverId = driver.id;
            const ambulanceId = driver.ambulance_id;

            if (!ambulanceId) {
                return res.status(400).json({ 
                    error: 'Driver does not have an assigned ambulance',
                    message: 'Please contact administrator to assign an ambulance before accepting requests'
                });
            }

            // Check if request exists and is pending
            AmbulanceRequest.findRequestById(requestId, (requestErr, requestResults) => {
                if (requestErr) {
                    return res.status(500).json({ error: requestErr.message });
                }
                if (requestResults.length === 0) {
                    return res.status(404).json({ error: 'Ambulance request not found' });
                }

                const request = requestResults[0];
                if (request.status !== 'pending') {
                    return res.status(400).json({ 
                        error: 'Request is not pending',
                        message: `Request status is '${request.status}'. Only pending requests can be self-assigned.`
                    });
                }

                // Check if dispatch already exists
                Dispatch.findByRequestId(requestId, (dispatchErr, dispatchResults) => {
                    if (dispatchErr) {
                        return res.status(500).json({ error: dispatchErr.message });
                    }
                    if (dispatchResults.length > 0) {
                        return res.status(400).json({ error: 'Request has already been assigned' });
                    }

                    // Create dispatch record
                    Dispatch.create({
                        ambulance_request_id: requestId,
                        ambulance_id: ambulanceId,
                        driver_id: driverId
                    }, (createErr, dispatchResults) => {
                        if (createErr) {
                            if (createErr.code === 'ER_DUP_ENTRY') {
                                return res.status(400).json({ error: 'Dispatch already exists for this request' });
                            }
                            if (createErr.code === 'ER_NO_REFERENCED_ROW_2') {
                                return res.status(400).json({ error: 'Invalid ambulance ID or driver ID' });
                            }
                            return res.status(500).json({ error: createErr.message });
                        }

                        // Update request status to 'dispatched'
                        AmbulanceRequest.updateStatus(requestId, 'dispatched', null, (updateErr) => {
                            if (updateErr) {
                                // Rollback: delete dispatch if status update fails
                                Dispatch.delete(dispatchResults.insertId, () => {});
                                return res.status(500).json({ error: updateErr.message });
                            }

                            const dispatchId = dispatchResults.insertId;
                            const requesterUserId = request.request_by;
                            const driverUserId = driver.user_id;

                            // Broadcast dispatch update via websocket
                            const broadcast = req.broadcastDispatch || (() => {});
                            broadcast({
                                request_id: Number(requestId),
                                ambulance_id: ambulanceId,
                                driver_id: driverId,
                                dispatch_id: dispatchId,
                                status: 'dispatched'
                            });

                            // Broadcast that request is assigned (removed from pending) to all drivers
                            const broadcastAssigned = req.broadcastRequestAssigned || (() => {});
                            broadcastAssigned(Number(requestId), {
                                dispatch_id: dispatchId,
                                ambulance_id: ambulanceId,
                                driver_id: driverId
                            });

                            const driverNotificationText = `You have self-assigned ambulance request #${requestId}. Dispatch ID: ${dispatchId}.`;
                            const requesterNotificationText = `Your ambulance request #${requestId} has been self-assigned. Dispatch ID: ${dispatchId}.`;

                            const driverPushPromise = sendPushToUser(driverUserId, {
                                notification: {
                                    title: 'New Dispatch',
                                    body: 'You have been assigned a new ambulance dispatch'
                                },
                                data: {
                                    type: 'driver-assigned',
                                    request_id: String(requestId),
                                    ambulance_id: String(ambulanceId),
                                    driver_id: String(driverId),
                                    dispatch_id: String(dispatchId)
                                }
                            }).catch((err) => {
                                console.error('Failed to send push notification to driver:', err.message);
                                return { error: err.message, skipped: true };
                            });

                            const requesterPushPromise = requesterUserId ? sendPushToUser(requesterUserId, {
                                notification: {
                                    title: 'Ambulance Dispatched',
                                    body: 'Your ambulance request has been dispatched'
                                },
                                data: {
                                    type: 'request-dispatched',
                                    request_id: String(requestId),
                                    ambulance_id: String(ambulanceId),
                                    driver_id: String(driverId),
                                    dispatch_id: String(dispatchId)
                                }
                            }).catch((err) => {
                                console.error('Failed to send push notification to requester:', err.message);
                                return { error: err.message, skipped: true };
                            }) : Promise.resolve(null);

                            const driverNotificationPromise = createNotificationRecord(
                                driverUserId,
                                driverNotificationText,
                                requestId
                            );
                            const requesterNotificationPromise = requesterUserId
                                ? createNotificationRecord(requesterUserId, requesterNotificationText, requestId)
                                : Promise.resolve(null);

                            Promise.all([
                                driverPushPromise,
                                requesterPushPromise,
                                driverNotificationPromise,
                                requesterNotificationPromise
                            ]).then(([driverPush, requesterPush, driverNotification, requesterNotification]) => {
                                return res.json({
                                    message: 'Request assigned successfully',
                                    dispatch_id: dispatchId,
                                    request_id: requestId,
                                    ambulance_id: ambulanceId,
                                    driver_id: driverId,
                                    push_delivery: {
                                        driver: driverPush,
                                        requester: requesterPush
                                    },
                                    notifications: {
                                        driver: driverNotification,
                                        requester: requesterNotification
                                    }
                                });
                            });
                        });
                    });
                });
            });
        });
    }
};

module.exports = driverController;


