import type { RequestHandler } from 'express';
import type { ZodType } from 'zod';
import { validationError } from '../lib/http-errors';

type Schemas = { body?: ZodType; query?: ZodType; params?: ZodType };

/**
 * Validates body / query / params with zod. Parsed values are stored on `res.locals.valid`
 * (Express 5 makes `req.query` read-only), and failures become field-level 400 errors.
 */
export const validate =
  (schemas: Schemas): RequestHandler =>
  (req, res, next) => {
    const valid: Record<string, unknown> = {};
    const fieldErrors: Record<string, string[]> = {};
    const formErrors: string[] = [];
    for (const part of ['params', 'query', 'body'] as const) {
      const schema = schemas[part];
      if (!schema) continue;
      const r = schema.safeParse(req[part] ?? {});
      if (r.success) valid[part] = r.data;
      else
        for (const issue of r.error.issues) {
          const key = issue.path.join('.');
          if (!key) formErrors.push(issue.message);
          else (fieldErrors[key] ??= []).push(issue.message);
        }
    }
    if (Object.keys(fieldErrors).length || formErrors.length)
      return next(validationError(fieldErrors, formErrors));
    res.locals.valid = valid;
    next();
  };
