import { describe, it, expect, vi } from 'vitest';
import express from 'express';
import request from 'supertest';
import { createConsoleAdminRouter } from './console-admin-api.js';

function mkApp(registry: any) {
  const app = express();
  app.use(express.json());
  app.use('/api/admin', createConsoleAdminRouter({
    registry,
    requireAdmin: (_req: any, _res: any, next: any) => next(),
  }));
  return app;
}

describe('console admin API', () => {
  it('lists active sessions', async () => {
    const registry = {
      listAll: () => [
        { localTaskId: 't1', connectionId: 'c1', ownerId: 'u1', startedAt: 1000,
          lastActivityAt: 2000, totalInputBytes: 10, totalOutputBytes: 20, isClosed: false },
      ],
    };
    const res = await request(mkApp(registry)).get('/api/admin/ssh/console-sessions');
    expect(res.status).toBe(200);
    expect(res.body.sessions).toHaveLength(1);
    expect(res.body.sessions[0].task_id).toBe('t1');
  });

  it('kills session by task id', async () => {
    const registry = {
      listAll: () => [],
      closeForTask: vi.fn(async () => {}),
    };
    const res = await request(mkApp(registry))
      .post('/api/admin/ssh/console-sessions/t1/kill')
      .send({ reason: 'investigating' });
    expect(res.status).toBe(200);
    expect(res.body.closed).toBe(true);
    expect(registry.closeForTask).toHaveBeenCalledWith('t1', 'admin_kill');
  });
});
