/**
 * Delivery routes
 */

const express = require('express');
const { requireAuth } = require('../middleware/auth.middleware');
const { create, getAll, getOne, update, deleteOne } = require('../controllers/delivery.controller');
const {
  deliveryCreateSchema,
  deliveryUpdateSchema,
  deliveryCodeSchema,
  validate
} = require('../utils/validators');

const router = express.Router();

router.use(requireAuth);

router.post('/', deliveryCreateSchema, (req, res, next) => {
  try {
    validate(req);
    return create(req, res).catch(next);
  } catch (e) {
    return next(e);
  }
});

router.get('/', getAll);

router.get('/:deliveryCode', deliveryCodeSchema, (req, res, next) => {
  try {
    validate(req);
    return getOne(req, res).catch(next);
  } catch (e) {
    return next(e);
  }
});

router.put('/:deliveryCode', deliveryCodeSchema, deliveryUpdateSchema, (req, res, next) => {
  try {
    validate(req);
    return update(req, res).catch(next);
  } catch (e) {
    return next(e);
  }
});

router.delete('/:deliveryCode', deliveryCodeSchema, (req, res, next) => {
  try {
    validate(req);
    return deleteOne(req, res).catch(next);
  } catch (e) {
    return next(e);
  }
});

module.exports = router;

