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

exports.addShipment = async (req, res) => {
  try {
    const { shipmentNumber, shipmentDate, shipmentStatus, destination, supplierId } = req.body;

    if (supplierId) {
      const supplier = await Supplier.findById(supplierId);
      if (!supplier) return res.status(404).json({ msg: 'Supplier not found' });
    }

    const newShipment = await Shipment.create({
      shipmentNumber,
      shipmentDate,
      shipmentStatus,
      destination,
      supplier: supplierId || null,
    });

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

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

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

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

    if (supplierId) {
      const supplier = await Supplier.findById(supplierId);
      if (!supplier) return res.status(404).json({ msg: 'Supplier not found' });
    }

    const updatedShipment = await Shipment.findByIdAndUpdate(
      req.params.id,
      {
        ...req.body,
        supplier: supplierId || null,
      },
      { new: true }
    );

    if (!updatedShipment) return res.status(404).json({ msg: 'Shipment not found' });

    res.status(200).json(updatedShipment);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to update shipment', error: error.message });
  }
};

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