const Delivery = require('../models/delivery');
const Shipment = require('../models/shipment');

exports.addDelivery = async (req, res) => {
  try {
    const { deliveryCode, deliveryDate, quantityDelivered, deliveryStatus, shipmentId } = req.body;

    if (shipmentId) {
      const shipment = await Shipment.findById(shipmentId);
      if (!shipment) return res.status(404).json({ msg: 'Shipment not found' });
    }

    const newDelivery = await Delivery.create({
      deliveryCode,
      deliveryDate,
      quantityDelivered,
      deliveryStatus,
      shipment: shipmentId || null,
    });

    res.status(201).json(newDelivery);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to add delivery', error: error.message });
  }
};

exports.getDeliveries = async (req, res) => {
  try {
    const deliveries = await Delivery.find().populate({ path: 'shipment', populate: 'supplier' });
    res.status(200).json(deliveries);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to fetch deliveries', error: error.message });
  }
};

exports.getDeliveryById = async (req, res) => {
  try {
    const delivery = await Delivery.findById(req.params.id).populate({ path: 'shipment', populate: 'supplier' });
    if (!delivery) return res.status(404).json({ msg: 'Delivery not found' });
    res.status(200).json(delivery);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to fetch delivery', error: error.message });
  }
};

exports.updateDelivery = async (req, res) => {
  try {
    const { shipmentId } = req.body;

    if (shipmentId) {
      const shipment = await Shipment.findById(shipmentId);
      if (!shipment) return res.status(404).json({ msg: 'Shipment not found' });
    }

    const updatedDelivery = await Delivery.findByIdAndUpdate(
      req.params.id,
      {
        ...req.body,
        shipment: shipmentId || null,
      },
      { new: true }
    );

    if (!updatedDelivery) return res.status(404).json({ msg: 'Delivery not found' });
    res.status(200).json(updatedDelivery);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to update delivery', error: error.message });
  }
};

exports.deleteDelivery = async (req, res) => {
  try {
    const deletedDelivery = await Delivery.findByIdAndDelete(req.params.id);
    if (!deletedDelivery) return res.status(404).json({ msg: 'Delivery not found' });
    res.status(200).json({ msg: 'Delivery deleted successfully' });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to delete delivery', error: error.message });
  }
};
