const Warehouse = require('../models/Warehouse');

exports.addwarehouse = async (req, res) => {
  try {
    const { warehouseCode, warehouseName, warehouseLocation } = req.body;
    const newWarehouse = await Warehouse.create({ warehouseCode, warehouseName, warehouseLocation });
    res.status(201).json({ msg: 'Warehouse added successfully', warehouse: newWarehouse });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to add warehouse', error: error.message });
  }
};

exports.getwarehouse = async (req, res) => {
  try {
    const warehouses = await Warehouse.find();
    res.status(200).json(warehouses);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to fetch warehouses', error: error.message });
  }
};

exports.getwarehousebyid = async (req, res) => {
  try {
    const warehouse = await Warehouse.findById(req.params.id);
    if (!warehouse) {
      return res.status(404).json({ msg: 'Warehouse not found' });
    }
    res.status(200).json(warehouse);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to fetch warehouse', error: error.message });
  }
};

exports.updatewarehouse = async (req, res) => {
  try {
    const warehouse = await Warehouse.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!warehouse) {
      return res.status(404).json({ msg: 'Warehouse not found' });
    }
    res.status(200).json({ msg: 'Warehouse updated successfully', warehouse });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to update warehouse', error: error.message });
  }
};

exports.deletewarehouse = async (req, res) => {
  try {
    const warehouse = await Warehouse.findByIdAndDelete(req.params.id);
    if (!warehouse) {
      return res.status(404).json({ msg: 'Warehouse not found' });
    }
    res.status(200).json({ msg: 'Warehouse deleted successfully' });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to delete warehouse', error: error.message });
  }
};
