// controllers/paymentController.js
const Payment = require('../models/Payment');

/**
 * Records a payment transaction for a labourer accepting a work order.
 * In a real-world scenario, this would involve integrating with a payment gateway.
 * For this implementation, it simulates a successful internal payment record.
 *
 * @param {string} labourerId - The ID of the labourer making the payment.
 * @param {string} workOrderId - The ID of the work order for which the payment is made.
 * @param {number} amount - The amount to be paid (e.g., 100 Rs).
 * @returns {object} - An object indicating success/failure and the created payment record.
 */
exports.recordLabourerAcceptanceFee = async (labourerId, workOrderId, amount) => {
    try {
        const newPayment = new Payment({
            labourerId,
            workOrderId,
            amount,
            currency: 'PKR',
            transactionType: 'debit',
            status: 'pending', // <-- CHANGED TO 'pending'
            description: `Acceptance fee for Work Order: ${workOrderId}`,
        });
        await newPayment.save();

        // --- REAL-TIME ADDITION: Notify Labourer of new pending payment ---
        // This function is called from workOrderController, so we need to pass req.app.io
        // For simplicity, let's assume `req` object (and thus `req.app.io`) is available
        // or passed down. If not, you'd need a different way to get `io` here.
        // For now, I'll add a placeholder comment. In a real app, you might pass `io` as an argument.
        // const io = req.app.get('io'); // This line would be here if `req` was available.
        // io.to(`laborer_${labourerId}`).emit('newPendingPayment', {
        //     payment: newPayment,
        //     message: 'A new pending payment has been recorded for your acceptance fee.'
        // });
        // console.log(`Emitted 'newPendingPayment' to laborer_${labourerId} for payment ${newPayment._id}`);
        // --- END REAL-TIME ADDITION ---

        return { success: true, payment: newPayment };
    } catch (error) {
        console.error(`[Payment Service] Error recording labourer acceptance fee for order ${workOrderId} and labourer ${labourerId}:`, error);
        return { success: false, error: error.message };
    }
};

/**
 * Fetches all pending payments for a specific labourer.
 * @param {object} req - Express request object (expects req.labour._id from middleware).
 * @param {object} res - Express response object.
 */
exports.getPendingPaymentsForLabourer = async (req, res) => {
    try {
        const labourerId = req.labour ? req.labour._id : null; // Defensive check

        if (!labourerId) {
            console.error('getPendingPaymentsForLabourer: req.labour or req.labour._id is undefined.');
            return res.status(401).json({ message: 'Authentication required: Labourer ID not found.' });
        }

        const pendingPayments = await Payment.find({
            labourerId,
            status: 'pending',
            transactionType: 'debit'
        }).sort({ createdAt: -1 });

        // --- REAL-TIME ADDITION: Emit initial pending payments via Socket.IO ---
        const io = req.app.get('io'); // Get the Socket.IO instance
        io.to(`laborer_${labourerId}`).emit('initialPendingPayments', {
            payments: pendingPayments,
            message: 'Your initial list of pending payments has been loaded.'
        });
        console.log(`Emitted 'initialPendingPayments' to laborer_${labourerId}`);
        // --- END REAL-TIME ADDITION ---

        res.json(pendingPayments);
    } catch (error) {
        console.error('Error fetching pending payments:', error);
        res.status(500).json({ message: 'Failed to fetch pending payments', error: error.message });
    }
};

/**
 * Fetches all cleared (completed) payments for a specific labourer.
 * @param {object} req - Express request object (expects req.labour._id from middleware).
 * @param {object} res - Express response object.
 */
exports.getClearedPaymentsForLabourer = async (req, res) => {
    try {
        const labourerId = req.labour ? req.labour._id : null; // Defensive check

        if (!labourerId) {
            console.error('getClearedPaymentsForLabourer: req.labour or req.labour._id is undefined.');
            return res.status(401).json({ message: 'Authentication required: Labourer ID not found.' });
        }

        const clearedPayments = await Payment.find({
            labourerId,
            status: 'completed',
            transactionType: 'debit'
        }).sort({ createdAt: -1 });

        // --- REAL-TIME ADDITION: Emit initial cleared payments via Socket.IO ---
        const io = req.app.get('io'); // Get the Socket.IO instance
        io.to(`laborer_${labourerId}`).emit('initialClearedPayments', {
            payments: clearedPayments,
            message: 'Your initial list of cleared payments has been loaded.'
        });
        console.log(`Emitted 'initialClearedPayments' to laborer_${labourerId}`);
        // --- END REAL-TIME ADDITION ---

        res.json(clearedPayments);
    } catch (error) {
        console.error('Error fetching cleared payments:', error);
        res.status(500).json({ message: 'Failed to fetch cleared payments', error: error.message });
    }
};

// You would also need a function to update payment status (e.g., from 'pending' to 'completed')
// This is where you'd emit 'paymentStatusUpdate' events.
/*
exports.updatePaymentStatus = async (req, res) => {
    try {
        const { paymentId } = req.params;
        const { newStatus } = req.body; // e.g., 'completed', 'failed'

        const payment = await Payment.findById(paymentId);
        if (!payment) {
            return res.status(404).json({ message: 'Payment not found' });
        }

        payment.status = newStatus;
        await payment.save();

        // --- REAL-TIME ADDITION: Notify Labourer of payment status change ---
        const io = req.app.get('io');
        io.to(`laborer_${payment.labourerId}`).emit('paymentStatusUpdate', {
            paymentId: payment._id,
            status: payment.status,
            message: `Payment ${payment._id} status changed to ${payment.status}.`
        });
        console.log(`Emitted 'paymentStatusUpdate' to laborer_${payment.labourerId} for payment ${payment._id}`);
        // --- END REAL-TIME ADDITION ---

        res.json({ message: 'Payment status updated successfully', payment });
    } catch (error) {
        console.error('Error updating payment status:', error);
        res.status(500).json({ message: 'Failed to update payment status', error: error.message });
    }
};
*/
