import { cookieNames } from '../auth/cookies.js';
import { requireAllowedOrigin } from './authRoutes.js';
export async function registerTotpRoutes(app, config, services) {
    app.post('/api/auth/totp/setup', { preHandler: (request, reply) => requireAllowedOrigin(config, request, reply) }, async (request, reply) => {
        const cookies = request.cookies;
        try {
            const result = await services.authService.setupTotp(cookies[cookieNames.session], request.ip);
            return result;
        }
        catch (error) {
            return sendAuthError(reply, error);
        }
    });
    app.post('/api/auth/totp/activate', { preHandler: (request, reply) => requireAllowedOrigin(config, request, reply) }, async (request, reply) => {
        const cookies = request.cookies;
        const { secret, otp } = request.body ?? {};
        if (typeof secret !== 'string' || typeof otp !== 'string') {
            return reply.code(400).send({ error: 'invalid_request' });
        }
        try {
            await services.authService.activateTotp(cookies[cookieNames.session], secret, otp, request.ip);
            return { totpEnabled: true };
        }
        catch (error) {
            return sendAuthError(reply, error);
        }
    });
    app.delete('/api/auth/totp', { preHandler: (request, reply) => requireAllowedOrigin(config, request, reply) }, async (request, reply) => {
        const cookies = request.cookies;
        try {
            await services.authService.disableTotp(cookies[cookieNames.session], request.ip);
            return { totpEnabled: false };
        }
        catch (error) {
            return sendAuthError(reply, error);
        }
    });
}
function sendAuthError(reply, error) {
    if (error instanceof Error && 'statusCode' in error && 'code' in error) {
        const authError = error;
        return reply.code(authError.statusCode).send({ error: authError.code.toLowerCase() });
    }
    throw error;
}
//# sourceMappingURL=totpRoutes.js.map