const express = require('express');
const { query } = require('../db');
const auth = require('../middleware/auth');

const router = express.Router();

router.get('/', auth(), async (req, res) => {
  const { companyId } = req.query;
  const rows = await query('SELECT id, company_id, name FROM departments WHERE (? IS NULL OR company_id = ?) ORDER BY id DESC', [companyId || null, companyId || null]);
  res.json(rows);
});

router.post('/', auth(), async (req, res) => {
  const { companyId, name } = req.body;
  if (!companyId || !name) return res.status(400).json({ error: 'companyId & name required' });
  await query('INSERT INTO departments (company_id, name) VALUES (?, ?)', [companyId, name]);
  res.status(201).json({ ok: true });
});

router.put('/:id', auth(), async (req, res) => {
  const { name } = req.body;
  await query('UPDATE departments SET name = ? WHERE id = ?', [name, req.params.id]);
  res.json({ ok: true });
});

router.delete('/:id', auth(), async (req, res) => {
  await query('DELETE FROM departments WHERE id = ?', [req.params.id]);
  res.json({ ok: true });
});

module.exports = router;
