/**
 * Explicit input validation hook for the API layer.
 * Call parseJson inside handlers; nothing is validated by magic.
 */
import { z } from 'zod';
import { AppError, type ErrorDetail } from './errors.js';

export function parseJson<T>(schema: z.ZodType<T>, input: unknown): T {
  const result = schema.safeParse(input);
  if (result.success) {
    return result.data;
  }
  const details: ReadonlyArray<ErrorDetail> = result.error.issues.map((issue) => ({
    path: issue.path.join('.'),
    message: issue.message,
  }));
  throw new AppError(400, 'VALIDATION_ERROR', 'Invalid request payload', details);
}
