const express = require('express');
const pool = require('../config/db');
const authMiddleware = require('../middleware/auth');

const router = express.Router();

router.get('/', authMiddleware, async (req, res) => {
  try {
    const [warehouses] = await pool.query('SELECT * FROM Warehouse ORDER BY warehouseCode');
    res.json(warehouses);
  } catch (error) {
    res.status(500).json({ message: 'Failed to fetch warehouses.', error: error.message });
  }
});

router.post('/', authMiddleware, async (req, res) => {
  try {
    const { warehouseCode, warehouseName, warehouseLocation } = req.body;

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

    await pool.query(
      'INSERT INTO Warehouse (warehouseCode, warehouseName, warehouseLocation) VALUES (?, ?, ?)',
      [warehouseCode, warehouseName, warehouseLocation]
    );

    res.status(201).json({ message: 'Warehouse added successfully.' });
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(409).json({ message: 'Warehouse code already exists.' });
    }
    res.status(500).json({ message: 'Failed to add warehouse.', error: error.message });
  }
});

module.exports = router;
