import Shipment from "../models/Shipment.js";

export const createShipment = async (req, res) => {
    try {
        const existing = await Shipment.findOne({ shipmentNumber: req.body.shipmentNumber });
        if (existing) return res.status(400).json({ message: "Shipment already exists" });

        const shipment = await Shipment.create(req.body);
        res.status(201).json(shipment);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

export const getAllShipments = async (req, res) => {
    try {
        const shipments = await Shipment.find().populate("supplier");
        res.status(200).json(shipments);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

export const getShipment = async (req, res) => {
    try {
        const shipment = await Shipment.findById(req.params.id).populate("supplier");
        res.status(200).json(shipment);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

export const updateShipment = async (req, res) => {
    try {
        const shipment = await Shipment.findByIdAndUpdate(req.params.id, req.body, { new: true });
        res.status(200).json(shipment);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

export const deleteShipment = async (req, res) => {
    try {
        await Shipment.findByIdAndDelete(req.params.id);
        res.status(200).json({ message: "Shipment deleted successfully" });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};