const AmbulanceRequest = require('../models/AmbulanceRequest');
const Notification = require('../models/Notification');
const { sendPushToUser } = require('../config/push');

const buildPushErrorSummary = (userId, error) => ({
    user_id: userId,
    attempted: 0,
    sent: 0,
    failed: 0,
    skipped: true,
    reason: 'unexpected-error',
    error: error?.message || String(error)
});

const statusController = {
    // Update status endpoint with notifications
    updateStatus: (req, res, sendNotification) => {
        const { request_id, status, comment } = req.body;
        
        if (!request_id || !status) {
            return res.status(400).json({ error: 'Request ID and status are required' });
        }

        // First, get the request details to know who made the request
        AmbulanceRequest.findRequestById(request_id, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            
            if (results.length === 0) {
                return res.status(200).json({ message: 'Ambulance request not found' });
            }
            
            const request = results[0];
            const userId = request.request_by;
            
            // Determine notification text based on status
            let notificationText = '';
            const normalizedStatus = status.toLowerCase();
            switch (normalizedStatus) {
                case 'dispatched':
                    notificationText = 'The ambulance has been dispatched';
                    break;
                case 'ongoing':
                case 'enroute':
                    notificationText = 'The driver has started the trip';
                    break;
                case 'cancelled':
                    notificationText = 'Your ambulance request has been cancelled';
                    break;
                case 'completed':
                    notificationText = 'The request has been closed successfully';
                    break;
                default:
                    notificationText = `Your ambulance request status has been updated to ${status}`;
            }
            
            // Add comment to notification text if provided
            if (comment) {
                notificationText += `. Comment: ${comment}`;
            }
            
            // Update the ambulance request status and comment
            AmbulanceRequest.updateStatus(request_id, status, comment, (err, updateResults) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }
                
                // Create a notification for the user (persist request_id so taps can resolve the trip)
                Notification.create({ user_id: userId, request_id, text: notificationText }, (err, notificationResults) => {
                    if (err) {
                        return res.status(500).json({ error: err.message });
                    }
                    
                    const notification = {
                        id: notificationResults.insertId,
                        user_id: userId,
                        request_id,
                        text: notificationText,
                        timestamp: new Date()
                    };
                    
                    // Send real-time notification via WebSocket
                    sendNotification(userId, notification);

                    // Send push notification and return delivery summary
                    sendPushToUser(userId, {
                        notification: {
                            title: 'Ambulance Request Update',
                            body: notificationText
                        },
                        data: {
                            type: 'request-status',
                            request_id: String(request_id),
                            status: status.toLowerCase()
                        }
                    })
                        .catch((err) => {
                            console.error('Failed to send push notification for status update:', err.message);
                            return buildPushErrorSummary(userId, err);
                        })
                        .then((pushResult) => {
                            res.json({ 
                                message: 'Status updated successfully and notification sent',
                                notification: notification,
                                push_delivery: pushResult
                            });
                        });
                });
            });
        });
    }
};

module.exports = statusController;



