import { Router } from 'express';
import { VLAN_ID } from '../config/env.js';
import { buildAcceptPayload, normalizeAttributes } from '../utils/attrs.js';
import { pushRequest } from '../sse.js';
import { activeSessions, sendRadiusSelfTest } from '../services/radius.js';

const router = Router();

router.post('/authorize', (req, res) => {
  const attrs = normalizeAttributes(req.body);
  const reply = buildAcceptPayload();
  pushRequest({
    id: Date.now() + ':' + Math.random().toString(16).slice(2),
    ts: new Date().toISOString(),
    type: 'authorize',
    attrs,
    decision: 'accept',
    vlan: VLAN_ID,
  });
  return res.status(200).json(reply);
});

router.post('/accounting', (req, res) => {
  const attrs = normalizeAttributes(req.body);
  try {
    const st = String(attrs['Acct-Status-Type'] || attrs['Acct-Status-Type*0'] || '').toUpperCase();
    const sessionId = String(attrs['Acct-Session-Id'] || '');
    const username = String(attrs['User-Name'] || '');
    if (sessionId && username) {
      if (st === 'START' || st === 'ALIVE' || st === 'INTERIM-UPDATE' || st === 'INTERIM') {
        activeSessions.set(sessionId, {
          username,
          sessionId,
          nasIp: attrs['NAS-IP-Address'] || '',
          nasId: attrs['NAS-Identifier'] || '',
          callingStationId: attrs['Calling-Station-Id'] || '',
          calledStationId: attrs['Called-Station-Id'] || '',
          updatedAt: Date.now(),
        });
      } else if (st === 'STOP') {
        activeSessions.delete(sessionId);
      }
    }
  } catch {}
  pushRequest({
    id: Date.now() + ':' + Math.random().toString(16).slice(2),
    ts: new Date().toISOString(),
    type: 'accounting',
    attrs,
  });
  return res.status(200).json({});
});

router.post('/authorize-inner', async (_req, res) => res.status(410).json({}));

router.post('/post-auth', async (req, res) => {
  try {
    const attrs = normalizeAttributes(req.body);
    pushRequest({
      id: Date.now() + ':' + Math.random().toString(16).slice(2),
      ts: new Date().toISOString(),
      type: 'post-auth',
      attrs,
    });
  } catch {}
  return res.status(200).json({});
});

router.post('/test/radius', async (_req, res) => {
  try {
    const result = await sendRadiusSelfTest();
    pushRequest({
      id: Date.now() + ':' + Math.random().toString(16).slice(2),
      ts: new Date().toISOString(),
      type: 'selftest',
      attrs: { 'User-Name': 'selftest-node' },
      decision: result.code,
    });
    res.json({ ok: true, result });
  } catch (err) {
    pushRequest({
      id: Date.now() + ':' + Math.random().toString(16).slice(2),
      ts: new Date().toISOString(),
      type: 'selftest',
      attrs: { 'User-Name': 'selftest-node' },
      decision: 'error',
      error: String(err && err.message || err),
    });
    res.status(500).json({ ok: false, error: String(err && err.message || err) });
  }
});

export default router;

