import Warehouse from '../models/Warehouse.js';

const createWarehouse = async (req, res) => {
  try {
    const { warehouseCode, warehouseName, warehouseLocation } = req.body;

    if (!warehouseCode || !warehouseName || !warehouseLocation) {
      return res.status(400).json({ message: 'All fields are required' });
    }

    const warehouseExists = await Warehouse.findOne({ warehouseCode });

    if (warehouseExists) {
      return res.status(400).json({ message: 'Warehouse code already exists' });
    }

    const warehouse = await Warehouse.create({
      warehouseCode,
      warehouseName,
      warehouseLocation,
    });

    res.status(201).json(warehouse);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const getAllWarehouses = async (req, res) => {
  try {
    const warehouses = await Warehouse.find({});
    res.json(warehouses);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const getSingleWarehouse = async (req, res) => {
  try {
    const warehouse = await Warehouse.findById(req.params.id);

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

    res.json(warehouse);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

export { createWarehouse, getAllWarehouses, getSingleWarehouse };
