const express = require('express');
const Delivery = require('../models/Delivery');
const Shipment = require('../models/Shipment');
const { protect } = require('../middleware/auth');
const { parseDateOnly } = require('../utils/dates');

const router = express.Router();

router.post('/', protect, async (req, res) => {
  try {
    const shipment = await Shipment.findOne({ shipmentNumber: req.body.shipmentNumber });
    if (!shipment) {
      return res.status(400).json({ message: 'Shipment number does not exist' });
    }

    const delivery = await Delivery.create({
      ...req.body,
      deliveryDate: parseDateOnly(req.body.deliveryDate),
    });
    res.status(201).json(delivery);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Delivery code already exists' });
    }
    res.status(400).json({ message: error.message });
  }
});

router.get('/', protect, async (req, res) => {
  try {
    const deliveries = await Delivery.find().sort({ deliveryDate: -1 });
    res.json(deliveries);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.get('/:deliveryCode', protect, async (req, res) => {
  try {
    const delivery = await Delivery.findOne({ deliveryCode: req.params.deliveryCode });
    if (!delivery) {
      return res.status(404).json({ message: 'Delivery not found' });
    }
    res.json(delivery);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.put('/:deliveryCode', protect, async (req, res) => {
  try {
    if (req.body.shipmentNumber) {
      const shipment = await Shipment.findOne({ shipmentNumber: req.body.shipmentNumber });
      if (!shipment) {
        return res.status(400).json({ message: 'Shipment number does not exist' });
      }
    }

    const { deliveryCode, ...updates } = req.body;
    if (req.body.deliveryDate) {
      updates.deliveryDate = parseDateOnly(req.body.deliveryDate);
    }

    const delivery = await Delivery.findOneAndUpdate(
      { deliveryCode: req.params.deliveryCode },
      updates,
      { new: true, runValidators: true }
    );

    if (!delivery) {
      return res.status(404).json({ message: 'Delivery not found' });
    }

    res.json(delivery);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

router.delete('/:deliveryCode', protect, async (req, res) => {
  try {
    const delivery = await Delivery.findOneAndDelete({ deliveryCode: req.params.deliveryCode });
    if (!delivery) {
      return res.status(404).json({ message: 'Delivery not found' });
    }
    res.json({ message: 'Delivery deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;
