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

const router = express.Router();

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

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

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

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

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

    const { shipmentNumber, ...updates } = req.body;
    if (req.body.shipmentDate) {
      updates.shipmentDate = parseDateOnly(req.body.shipmentDate);
    }

    const shipment = await Shipment.findOneAndUpdate(
      { shipmentNumber: req.params.shipmentNumber },
      updates,
      { new: true, runValidators: true }
    );

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

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

router.delete('/:shipmentNumber', protect, async (req, res) => {
  try {
    const linkedDelivery = await Delivery.findOne({ shipmentNumber: req.params.shipmentNumber });
    if (linkedDelivery) {
      return res.status(400).json({ message: 'Cannot delete shipment linked to deliveries' });
    }

    const shipment = await Shipment.findOneAndDelete({ shipmentNumber: req.params.shipmentNumber });
    if (!shipment) {
      return res.status(404).json({ message: 'Shipment not found' });
    }
    res.json({ message: 'Shipment deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;
