import { httpRouter } from 'convex/server';
import { authComponent, createAuth } from './auth';
import { httpAction } from './_generated/server';
import { api } from './_generated/api';
import { getClientIP } from './utils/getClientIP';

const http = httpRouter();

// Action HTTP para análise de segurança de requisições
// Pode ser chamada do frontend ou de outros sistemas
http.route({
	path: '/security/analyze',
	method: 'POST',
	handler: httpAction(async (ctx, request) => {
		const url = new URL(request.url);
		const method = request.method;

		// Extrair IP do cliente
		const ipOrigem = getClientIP(request);

		// Extrair headers
		const headers: Record<string, string> = {};
		request.headers.forEach((value, key) => {
			headers[key] = value;
		});

		// Extrair query params
		const queryParams: Record<string, string> = {};
		url.searchParams.forEach((value, key) => {
			queryParams[key] = value;
		});

		// Extrair body se disponível
		let body: string | undefined;
		try {
			body = await request.text();
		} catch {
			// Ignorar erros ao ler body
		}

		// Analisar requisição para detectar ataques
		const resultado = await ctx.runMutation(api.security.analisarRequisicaoHTTP, {
			url: url.pathname + url.search,
			method,
			headers,
			body,
			queryParams,
			ipOrigem,
			userAgent: request.headers.get('user-agent') ?? undefined
		});

		return new Response(JSON.stringify(resultado), {
			status: 200,
			headers: { 'Content-Type': 'application/json' }
		});
	})
});

// Seed de rate limit para ambiente de desenvolvimento
http.route({
	path: '/security/rate-limit/seed-dev',
	method: 'POST',
	handler: httpAction(async (ctx) => {
		const resultado = await ctx.runMutation(api.security.seedRateLimitDev, {});
		return new Response(JSON.stringify(resultado), {
			status: 200,
			headers: { 'Content-Type': 'application/json' }
		});
	})
});

authComponent.registerRoutes(http, createAuth);

export default http;
