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

const router = express.Router();

router.post('/', protect, async (req, res) => {
  try {
    const supplier = await Supplier.create(req.body);
    res.status(201).json(supplier);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Supplier code already exists' });
    }
    res.status(400).json({ message: error.message });
  }
});

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

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

router.put('/:supplierCode', protect, async (req, res) => {
  try {
    const { supplierCode, ...updates } = req.body;

    const supplier = await Supplier.findOneAndUpdate(
      { supplierCode: req.params.supplierCode },
      updates,
      { new: true, runValidators: true }
    );

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

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

router.delete('/:supplierCode', protect, async (req, res) => {
  try {
    const linkedShipment = await Shipment.findOne({ supplierCode: req.params.supplierCode });
    if (linkedShipment) {
      return res.status(400).json({ message: 'Cannot delete supplier linked to shipments' });
    }

    const supplier = await Supplier.findOneAndDelete({ supplierCode: req.params.supplierCode });
    if (!supplier) {
      return res.status(404).json({ message: 'Supplier not found' });
    }

    res.json({ message: 'Supplier deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;
