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

const router = express.Router();

// Sites represent geofenced locations
router.get('/', auth(), async (req, res) => {
  const { companyId } = req.query;
  const rows = await query('SELECT id, company_id, name, latitude, longitude, radius_m FROM sites 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, latitude, longitude, radius_m = 100 } = req.body;
  if (!companyId || !name || latitude == null || longitude == null) return res.status(400).json({ error: 'Missing fields' });
  await query('INSERT INTO sites (company_id, name, latitude, longitude, radius_m) VALUES (?, ?, ?, ?, ?)', [companyId, name, latitude, longitude, radius_m]);
  res.status(201).json({ ok: true });
});

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

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

module.exports = router;
