var Shipment = require("../models/Shipment");
var Supplier = require("../models/Supplier");
var Delivery = require("../models/Delivery");

function createShipment(req, res) {
  var supplier = req.body.supplier;
  var shipmentNumber = req.body.shipmentNumber;
  var shipmentDate = req.body.shipmentDate;
  var shipmentStatus = req.body.shipmentStatus;
  var destination = req.body.destination;

  if (!supplier || !shipmentNumber || !shipmentDate || !shipmentStatus || !destination) {
    return res.status(400).json({ message: "All shipment fields are required" });
  }

  Supplier.findById(supplier)
    .then(function (supplierExists) {
      if (!supplierExists) {
        return { supplierNotFound: true };
      }

      return Shipment.findOne({ shipmentNumber: shipmentNumber });
    })
    .then(function (shipmentExists) {
      if (shipmentExists && shipmentExists.supplierNotFound) {
        return res.status(404).json({ message: "Selected supplier was not found" });
      }

      if (shipmentExists) {
        return res.status(409).json({ message: "Shipment number already exists" });
      }

      return Shipment.create({
        supplier: supplier,
        shipmentNumber: shipmentNumber,
        shipmentDate: shipmentDate,
        shipmentStatus: shipmentStatus,
        destination: destination,
      });
    })
    .then(function (shipment) {
      if (!shipment) {
        return;
      }

      res.status(201).json({ message: "Shipment inserted successfully", shipment: shipment });
    })
    .catch(function (error) {
      res.status(500).json({ message: "Failed to insert shipment", error: error.message });
    });
}

function getShipments(req, res) {
  Shipment.find()
    .populate("supplier", "supplierCode supplierName telephone")
    .sort({ createdAt: -1 })
    .then(function (shipments) {
      res.status(200).json(shipments);
    })
    .catch(function (error) {
      res.status(500).json({ message: "Failed to get shipments", error: error.message });
    });
}

function updateShipment(req, res) {
  var id = req.params.id;
  var supplier = req.body.supplier;
  var shipmentNumber = req.body.shipmentNumber;
  var shipmentDate = req.body.shipmentDate;
  var shipmentStatus = req.body.shipmentStatus;
  var destination = req.body.destination;

  if (!supplier || !shipmentNumber || !shipmentDate || !shipmentStatus || !destination) {
    return res.status(400).json({ message: "All shipment fields are required" });
  }

  Supplier.findById(supplier)
    .then(function (supplierExists) {
      if (!supplierExists) {
        return { supplierNotFound: true };
      }

      return Shipment.findOne({
        shipmentNumber: shipmentNumber,
        _id: { $ne: id },
      });
    })
    .then(function (duplicateShipment) {
      if (duplicateShipment && duplicateShipment.supplierNotFound) {
        return res.status(404).json({ message: "Selected supplier was not found" });
      }

      if (duplicateShipment) {
        return res.status(409).json({ message: "Shipment number already exists" });
      }

      return Shipment.findByIdAndUpdate(
        id,
        {
          supplier: supplier,
          shipmentNumber: shipmentNumber,
          shipmentDate: shipmentDate,
          shipmentStatus: shipmentStatus,
          destination: destination,
        },
        { new: true, runValidators: true }
      );
    })
    .then(function (shipment) {
      if (!shipment) {
        return;
      }

      res.status(200).json({ message: "Shipment updated successfully", shipment: shipment });
    })
    .catch(function (error) {
      res.status(500).json({ message: "Failed to update shipment", error: error.message });
    });
}

function deleteShipment(req, res) {
  var id = req.params.id;

  Shipment.findByIdAndDelete(id)
    .then(function (shipment) {
      if (!shipment) {
        return null;
      }

      return Delivery.deleteMany({ shipment: id });
    })
    .then(function (result) {
      if (!result) {
        return res.status(404).json({ message: "Shipment not found" });
      }

      res.status(200).json({ message: "Shipment deleted successfully" });
    })
    .catch(function (error) {
      res.status(500).json({ message: "Failed to delete shipment", error: error.message });
    });
}

module.exports = {
  createShipment: createShipment,
  getShipments: getShipments,
  updateShipment: updateShipment,
  deleteShipment: deleteShipment,
};
