import { Router } from 'express';
import db from '../db.js';

const router = Router();

// GET /api/rules
router.get('/', (_req, res) => {
  const rows = db.prepare('SELECT * FROM rules ORDER BY sort_order, id').all();
  res.json(rows);
});

// POST /api/rules
router.post('/', (req, res) => {
  const { type, value, action, comment } = req.body;
  if (!type || !value) return res.status(400).json({ error: 'type and value are required' });

  const maxOrder = db.prepare('SELECT MAX(sort_order) as m FROM rules').get() as any;
  const sortOrder = (maxOrder?.m ?? -1) + 1;

  const result = db.prepare(
    'INSERT INTO rules (type, value, action, comment, sort_order) VALUES (?, ?, ?, ?, ?)'
  ).run(type, value, action || 'PROXY', comment || null, sortOrder);

  res.json({ id: result.lastInsertRowid });
});

// PUT /api/rules/reorder — MUST be before /:id
router.put('/reorder', (req, res) => {
  const { ids } = req.body;
  if (!Array.isArray(ids)) return res.status(400).json({ error: 'ids must be array' });

  const stmt = db.prepare('UPDATE rules SET sort_order = ? WHERE id = ?');
  const reorder = db.transaction(() => {
    ids.forEach((id: number, index: number) => {
      stmt.run(index, id);
    });
  });
  reorder();
  res.json({ ok: true });
});

// PUT /api/rules/:id
router.put('/:id', (req, res) => {
  const { id } = req.params;
  const { type, value, action, comment, enabled } = req.body;
  const rule = db.prepare('SELECT * FROM rules WHERE id = ?').get(id) as any;
  if (!rule) return res.status(404).json({ error: 'not found' });

  db.prepare('UPDATE rules SET type = ?, value = ?, action = ?, comment = ?, enabled = ? WHERE id = ?')
    .run(
      type ?? rule.type,
      value ?? rule.value,
      action ?? rule.action,
      comment ?? rule.comment,
      enabled ?? rule.enabled,
      id
    );
  res.json({ ok: true });
});

// DELETE /api/rules/:id
router.delete('/:id', (req, res) => {
  const { id } = req.params;
  db.prepare('DELETE FROM rules WHERE id = ?').run(id);
  res.json({ ok: true });
});

export default router;
