import { Router } from 'express';
import { VLAN_ID } from '../config/env.js';
import { clearRequests, getRecentRequests, registerSse } from '../sse.js';
import { deleteUserFromDb, readUsersFromDb, upsertUserToDb } from '../services/db.js';
import { disconnectUserSessions } from '../services/radius.js';

const router = Router();

// Users
router.get('/users', async (_req, res) => {
  const items = await readUsersFromDb();
  res.json({ items });
});

router.post('/users', async (req, res) => {
  const { username, password, vlan, disabled } = req.body || {};
  if (!username || !password) return res.status(400).json({ ok: false, error: 'username and password required' });
  const user = { username: String(username), password: String(password), vlan: String(vlan || VLAN_ID), disabled: !!disabled };
  await upsertUserToDb(user);
  res.json({ ok: true });
});

router.patch('/users/:username', async (req, res) => {
  const uname = String(req.params.username);
  const { password, vlan, disabled } = req.body || {};
  const current = (await readUsersFromDb()).find(u => u.username === uname);
  if (!current) return res.status(404).json({ ok: false, error: 'not_found' });
  const next = {
    username: uname,
    password: password !== undefined ? String(password) : current.password,
    vlan: vlan !== undefined ? String(vlan) : current.vlan,
    disabled: disabled !== undefined ? !!disabled : current.disabled,
  };
  await upsertUserToDb(next);
  if (disabled === true) {
    disconnectUserSessions(uname).catch(err => console.error('CoA disconnect error:', err));
  }
  res.json({ ok: true });
});

router.delete('/users/:username', async (req, res) => {
  const uname = String(req.params.username);
  await deleteUserFromDb(uname);
  res.json({ ok: true });
});

// Requests
router.get('/requests', (_req, res) => {
  res.json({ items: getRecentRequests() });
});

router.delete('/requests', (_req, res) => {
  clearRequests();
  res.json({ ok: true });
});

router.get('/requests.csv', (_req, res) => {
  const items = getRecentRequests();
  const cols = ['ts','type','user','nas','calling','called','decision','vlan','bw_down','bw_up'];
  const lines = [cols.join(',')];
  for (const ev of items) {
    const attrs = ev.attrs || {};
    const row = [
      ev.ts || '',
      ev.type || '',
      attrs['User-Name'] || attrs['User-Name*0'] || '',
      attrs['NAS-IP-Address'] || attrs['NAS-Identifier'] || '',
      attrs['Calling-Station-Id'] || '',
      attrs['Called-Station-Id'] || '',
      ev.decision || '',
      ev.vlan || '',
      (ev.bandwidth && ev.bandwidth.down) || '',
      (ev.bandwidth && ev.bandwidth.up) || ''
    ];
    const esc = (v) => String(v).includes(',') || String(v).includes('"') || String(v).includes('\n')
      ? '"' + String(v).replace(/"/g, '""') + '"'
      : String(v);
    lines.push(row.map(esc).join(','));
  }
  const csv = lines.join('\n');
  const ts = new Date().toISOString().replace(/[:T]/g, '-').split('.')[0];
  res.setHeader('Content-Type', 'text/csv; charset=utf-8');
  res.setHeader('Content-Disposition', `attachment; filename="radius-events-${ts}.csv"`);
  res.send(csv);
});

// SSE events
router.get('/events', (req, res) => {
  registerSse(req, res, {});
});

export default router;
