/**
 * Delivery controller
 */

const {
  createDelivery,
  getAllDeliveries,
  getDeliveryByCode,
  updateDelivery,
  deleteDelivery
} = require('../models/delivery.model');

async function create(req, res) {
  const delivery = await createDelivery(req.body);
  return res.status(201).json(delivery);
}

async function getAll(_req, res) {
  const deliveries = await getAllDeliveries();
  return res.json({ data: deliveries });
}

async function getOne(req, res) {
  const delivery = await getDeliveryByCode(req.params.deliveryCode);
  if (!delivery) return res.status(404).json({ error: 'NOT_FOUND', message: 'Delivery not found' });
  return res.json(delivery);
}

async function update(req, res) {
  const updated = await updateDelivery({ deliveryCode: req.params.deliveryCode, ...req.body });
  if (!updated) return res.status(404).json({ error: 'NOT_FOUND', message: 'Delivery not found' });
  return res.json(updated);
}

async function deleteOne(req, res) {
  const ok = await deleteDelivery(req.params.deliveryCode);
  if (!ok) return res.status(404).json({ error: 'NOT_FOUND', message: 'Delivery not found' });
  return res.status(204).send();
}

module.exports = { create, getAll, getOne, update, deleteOne };

