function formatIssues(issues) {
  return issues.map((issue) => ({
    path: issue.path.join('.'),
    message: issue.message,
  }));
}

function validate({ body, params, query }) {
  return (req, res, next) => {
    const errors = {};

    if (body) {
      const result = body.safeParse(req.body ?? {});
      if (!result.success) {
        errors.body = formatIssues(result.error.issues);
      } else {
        req.body = result.data;
      }
    }

    if (params) {
      const result = params.safeParse(req.params ?? {});
      if (!result.success) {
        errors.params = formatIssues(result.error.issues);
      } else {
        req.params = result.data;
      }
    }

    if (query) {
      const result = query.safeParse(req.query ?? {});
      if (!result.success) {
        errors.query = formatIssues(result.error.issues);
      } else {
        req.query = result.data;
      }
    }

    if (Object.keys(errors).length > 0) {
      return res.status(400).json({ error: 'Validation failed', details: errors });
    }

    return next();
  };
}

module.exports = { validate };
