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

const router = express.Router();

router.get('/', auth(), async (req, res) => {
  const rows = await query('SELECT id, name FROM companies ORDER BY id DESC');
  res.json(rows);
});

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

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

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

module.exports = router;
