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

function createSupplier(req, res) {
  var supplierCode = req.body.supplierCode;
  var supplierName = req.body.supplierName;
  var telephone = req.body.telephone;
  var address = req.body.address;
  var email = req.body.email;

  if (!supplierCode || !supplierName || !telephone || !address || !email) {
    return res.status(400).json({ message: "All supplier fields are required" });
  }

  Supplier.findOne({
    $or: [{ supplierCode: supplierCode }, { email: email }],
  })
    .then(function (supplierExists) {
      if (supplierExists) {
        return res.status(409).json({ message: "Supplier code or email already exists" });
      }

      return Supplier.create({
        supplierCode: supplierCode,
        supplierName: supplierName,
        telephone: telephone,
        address: address,
        email: email,
      });
    })
    .then(function (supplier) {
      if (!supplier) {
        return;
      }

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

function getSuppliers(req, res) {
  Supplier.find()
    .sort({ createdAt: -1 })
    .then(function (suppliers) {
      res.status(200).json(suppliers);
    })
    .catch(function (error) {
      res.status(500).json({ message: "Failed to get suppliers", error: error.message });
    });
}

module.exports = {
  createSupplier: createSupplier,
  getSuppliers: getSuppliers,
};
