import { createLogger } from '@4runr/shared';
import { getCorrelationId } from './correlationId.js';
const logger = createLogger('Gateway:Validation');
function formatZodError(error) {
    const fieldErrors = {};
    const formErrors = [];
    for (const issue of error.issues) {
        if (issue.path.length === 0) {
            formErrors.push(issue.message);
        }
        else {
            const path = issue.path.join('.');
            if (!fieldErrors[path]) {
                fieldErrors[path] = [];
            }
            fieldErrors[path].push(issue.message);
        }
    }
    return {
        fieldErrors,
        formErrors,
    };
}
export function validateBody(schema) {
    return async (request, reply) => {
        try {
            const result = schema.safeParse(request.body);
            if (!result.success) {
                const correlationId = getCorrelationId(request);
                reply.status(400).send({
                    error: 'invalid_request',
                    message: 'Request body validation failed',
                    details: formatZodError(result.error),
                    timestamp: new Date().toISOString(),
                    path: request.url,
                    statusCode: 400,
                    ...(correlationId && { correlationId }),
                });
                return;
            }
            request.body = result.data;
        }
        catch (error) {
            logger.error('Body validation error', { error: error instanceof Error ? error.message : String(error) });
            const correlationId = getCorrelationId(request);
            reply.status(500).send({
                error: 'server_error',
                message: 'Failed to validate request body',
                timestamp: new Date().toISOString(),
                path: request.url,
                statusCode: 500,
                ...(correlationId && { correlationId }),
            });
        }
    };
}
export function validateQuery(schema) {
    return async (request, reply) => {
        try {
            const result = schema.safeParse(request.query);
            if (!result.success) {
                const correlationId = getCorrelationId(request);
                reply.status(400).send({
                    error: 'invalid_query',
                    message: 'Query parameter validation failed',
                    details: formatZodError(result.error),
                    timestamp: new Date().toISOString(),
                    path: request.url,
                    statusCode: 400,
                    ...(correlationId && { correlationId }),
                });
                return;
            }
            request.query = result.data;
        }
        catch (error) {
            logger.error('Query validation error', { error: error instanceof Error ? error.message : String(error) });
            const correlationId = getCorrelationId(request);
            reply.status(500).send({
                error: 'server_error',
                message: 'Failed to validate query parameters',
                timestamp: new Date().toISOString(),
                path: request.url,
                statusCode: 500,
                ...(correlationId && { correlationId }),
            });
        }
    };
}
export function validateParams(schema) {
    return async (request, reply) => {
        try {
            const result = schema.safeParse(request.params);
            if (!result.success) {
                const correlationId = getCorrelationId(request);
                reply.status(400).send({
                    error: 'invalid_params',
                    message: 'Route parameter validation failed',
                    details: formatZodError(result.error),
                    timestamp: new Date().toISOString(),
                    path: request.url,
                    statusCode: 400,
                    ...(correlationId && { correlationId }),
                });
                return;
            }
            request.params = result.data;
        }
        catch (error) {
            logger.error('Params validation error', { error: error instanceof Error ? error.message : String(error) });
            const correlationId = getCorrelationId(request);
            reply.status(500).send({
                error: 'server_error',
                message: 'Failed to validate route parameters',
                timestamp: new Date().toISOString(),
                path: request.url,
                statusCode: 500,
                ...(correlationId && { correlationId }),
            });
        }
    };
}
export function validateHeaders(schema) {
    return async (request, reply) => {
        try {
            const result = schema.safeParse(request.headers);
            if (!result.success) {
                const correlationId = getCorrelationId(request);
                reply.status(400).send({
                    error: 'invalid_headers',
                    message: 'Header validation failed',
                    details: formatZodError(result.error),
                    timestamp: new Date().toISOString(),
                    path: request.url,
                    statusCode: 400,
                    ...(correlationId && { correlationId }),
                });
                return;
            }
            request.validatedHeaders = result.data;
        }
        catch (error) {
            logger.error('Headers validation error', { error: error instanceof Error ? error.message : String(error) });
            const correlationId = getCorrelationId(request);
            reply.status(500).send({
                error: 'server_error',
                message: 'Failed to validate headers',
                timestamp: new Date().toISOString(),
                path: request.url,
                statusCode: 500,
                ...(correlationId && { correlationId }),
            });
        }
    };
}
//# sourceMappingURL=validate.js.map