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

function createDelivery(req, res) {
  var shipment = req.body.shipment;
  var deliveryCode = req.body.deliveryCode;
  var deliveryDate = req.body.deliveryDate;
  var quantityDelivered = req.body.quantityDelivered;
  var deliveryStatus = req.body.deliveryStatus;

  if (!shipment || !deliveryCode || !deliveryDate || !quantityDelivered || !deliveryStatus) {
    return res.status(400).json({ message: "All delivery fields are required" });
  }

  Shipment.findById(shipment)
    .then(function (shipmentExists) {
      if (!shipmentExists) {
        return { shipmentNotFound: true };
      }

      return Delivery.findOne({ deliveryCode: deliveryCode });
    })
    .then(function (deliveryExists) {
      if (deliveryExists && deliveryExists.shipmentNotFound) {
        return res.status(404).json({ message: "Selected shipment was not found" });
      }

      if (deliveryExists) {
        return res.status(409).json({ message: "Delivery code already exists" });
      }

      return Delivery.create({
        shipment: shipment,
        deliveryCode: deliveryCode,
        deliveryDate: deliveryDate,
        quantityDelivered: quantityDelivered,
        deliveryStatus: deliveryStatus,
      });
    })
    .then(function (delivery) {
      if (!delivery) {
        return;
      }

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

function getDeliveries(req, res) {
  Delivery.find()
    .populate({
      path: "shipment",
      select: "shipmentNumber destination shipmentDate supplier",
      populate: { path: "supplier", select: "supplierName supplierCode" },
    })
    .sort({ createdAt: -1 })
    .then(function (deliveries) {
      res.status(200).json(deliveries);
    })
    .catch(function (error) {
      res.status(500).json({ message: "Failed to get deliveries", error: error.message });
    });
}

function updateDelivery(req, res) {
  var id = req.params.id;
  var shipment = req.body.shipment;
  var deliveryCode = req.body.deliveryCode;
  var deliveryDate = req.body.deliveryDate;
  var quantityDelivered = req.body.quantityDelivered;
  var deliveryStatus = req.body.deliveryStatus;

  if (!shipment || !deliveryCode || !deliveryDate || !quantityDelivered || !deliveryStatus) {
    return res.status(400).json({ message: "All delivery fields are required" });
  }

  Shipment.findById(shipment)
    .then(function (shipmentExists) {
      if (!shipmentExists) {
        return { shipmentNotFound: true };
      }

      return Delivery.findOne({
        deliveryCode: deliveryCode,
        _id: { $ne: id },
      });
    })
    .then(function (duplicateDelivery) {
      if (duplicateDelivery && duplicateDelivery.shipmentNotFound) {
        return res.status(404).json({ message: "Selected shipment was not found" });
      }

      if (duplicateDelivery) {
        return res.status(409).json({ message: "Delivery code already exists" });
      }

      return Delivery.findByIdAndUpdate(
        id,
        {
          shipment: shipment,
          deliveryCode: deliveryCode,
          deliveryDate: deliveryDate,
          quantityDelivered: quantityDelivered,
          deliveryStatus: deliveryStatus,
        },
        { new: true, runValidators: true }
      );
    })
    .then(function (delivery) {
      if (!delivery) {
        return;
      }

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

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

  Delivery.findByIdAndDelete(id)
    .then(function (delivery) {
      if (!delivery) {
        return res.status(404).json({ message: "Delivery not found" });
      }

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

module.exports = {
  createDelivery: createDelivery,
  getDeliveries: getDeliveries,
  updateDelivery: updateDelivery,
  deleteDelivery: deleteDelivery,
};
