import { getSessionsService } from './index.mjs';

export function registerSessionRoutes({ app, routes, deps }) {
  routes.register(app, {
    id: 'sessions.admin.list', method: 'GET', path: '/api/admin/sessions', owner: 'vendoo.sessions', policy: 'sessions.manage', csrf: false, stability: 'stable',
    handler: async (_req, res) => res.json(getSessionsService().listAll()),
  });
  routes.register(app, {
    id: 'sessions.admin.revoke', method: 'DELETE', path: '/api/admin/sessions/:id', owner: 'vendoo.sessions', policy: 'sessions.manage', csrf: true, stability: 'stable',
    handler: async (req, res) => {
      const session = getSessionsService().revokeAsAdmin(Number(req.params.id));
      deps.auditLog(req.user.id, req.user.email, 'session.destroyed', 'session', String(session.id), null, deps.getClientIp(req));
      res.json({ ok: true });
    },
  });
  routes.register(app, {
    id: 'sessions.admin.revoke-user', method: 'DELETE', path: '/api/admin/users/:id/sessions', owner: 'vendoo.sessions', policy: 'sessions.manage', csrf: true, stability: 'stable',
    handler: async (req, res) => {
      getSessionsService().revokeAllForUser(Number(req.params.id));
      deps.auditLog(req.user.id, req.user.email, 'sessions.destroyed_all', 'user', String(req.params.id), null, deps.getClientIp(req));
      res.json({ ok: true });
    },
  });
  routes.register(app, {
    id: 'sessions.admin.cleanup', method: 'POST', path: '/api/admin/sessions/cleanup', owner: 'vendoo.sessions', policy: 'sessions.manage', csrf: true, stability: 'stable',
    handler: async (req, res) => {
      getSessionsService().cleanup();
      deps.auditLog(req.user.id, req.user.email, 'sessions.cleanup', null, null, null, deps.getClientIp(req));
      res.json({ ok: true, message: 'Abgelaufene Sessions bereinigt' });
    },
  });
  routes.register(app, {
    id: 'sessions.self.list', method: 'GET', path: '/api/my/sessions', owner: 'vendoo.sessions', policy: 'sessions.self', csrf: false, stability: 'stable',
    handler: async (req, res) => res.json(getSessionsService().listForUser(req.user.id)),
  });
  routes.register(app, {
    id: 'sessions.self.revoke', method: 'DELETE', path: '/api/my/sessions/:id', owner: 'vendoo.sessions', policy: 'sessions.self', csrf: true, stability: 'stable',
    handler: async (req, res) => {
      const session = getSessionsService().revokeOwn(req.user.id, Number(req.params.id));
      deps.auditLog(req.user.id, req.user.email, 'session.destroyed_own', 'session', String(session.id), null, deps.getClientIp(req));
      res.json({ ok: true });
    },
  });
}
