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

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

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

export const getAllDeliveries = async (req, res) => {
    try {
        const deliveries = await Delivery.find().populate("shipment");
        res.status(200).json(deliveries);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

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

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

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