import { AuthError } from '../auth/authService.js';
import { cookieNames } from '../auth/cookies.js';
import { requireAllowedOrigin } from './authRoutes.js';
import { authenticateTerminalRequest } from './terminalRoutes.js';
export async function registerSecurityRoutes(app, config, services) {
    app.get('/api/auth/devices', async (request, reply) => {
        const auth = await authenticateTerminalRequest(services.authService, request, reply);
        if (!auth)
            return reply;
        const deviceToken = request.cookies[cookieNames.device];
        return { devices: await services.authService.listTrustedDevices(deviceToken) };
    });
    app.delete('/api/auth/devices/:id', { preHandler: (request, reply) => requireAllowedOrigin(config, request, reply) }, async (request, reply) => {
        const auth = await authenticateTerminalRequest(services.authService, request, reply);
        if (!auth)
            return reply;
        await services.authService.revokeTrustedDevice(request.params.id);
        return reply.code(204).send();
    });
    app.get('/api/auth/networks', async (request, reply) => {
        const auth = await authenticateTerminalRequest(services.authService, request, reply);
        if (!auth)
            return reply;
        return { networks: await services.authService.listIpRules() };
    });
    app.post('/api/auth/networks', { preHandler: (request, reply) => requireAllowedOrigin(config, request, reply) }, async (request, reply) => {
        const auth = await authenticateTerminalRequest(services.authService, request, reply);
        if (!auth)
            return reply;
        const value = request.body?.value;
        if (typeof value !== 'string' || !value.trim()) {
            return reply.code(400).send({ error: 'value_required' });
        }
        try {
            const rule = await services.authService.addIpRule(value, typeof request.body?.label === 'string' ? request.body.label : '');
            return reply.code(201).send({ network: rule });
        }
        catch (error) {
            if (error instanceof AuthError) {
                return reply.code(error.statusCode).send({ error: error.code.toLowerCase() });
            }
            throw error;
        }
    });
    app.delete('/api/auth/networks/:id', { preHandler: (request, reply) => requireAllowedOrigin(config, request, reply) }, async (request, reply) => {
        const auth = await authenticateTerminalRequest(services.authService, request, reply);
        if (!auth)
            return reply;
        await services.authService.removeIpRule(request.params.id);
        return reply.code(204).send();
    });
}
//# sourceMappingURL=securityRoutes.js.map