import { Router } from 'express';
import { randomUUID } from 'crypto';
import { getDb } from '../db';

export const configsRouter = Router();

configsRouter.get('/', (_req, res) => {
  const rows = getDb().prepare('SELECT * FROM configs ORDER BY key').all();
  res.json(rows);
});

configsRouter.get('/:key', (req, res) => {
  const row = getDb().prepare('SELECT * FROM configs WHERE key = ?').get(req.params.key);
  if (!row) return res.status(404).json({ error: 'Config not found' });
  res.json(row);
});

configsRouter.put('/:key', (req, res) => {
  const { value } = req.body;
  getDb().prepare(`
    INSERT INTO configs (id, key, value, updated_at)
    VALUES (?, ?, ?, datetime('now'))
    ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
  `).run(randomUUID(), req.params.key, JSON.stringify(value));
  res.json({ key: req.params.key, ok: true });
});
