function validate(schema, source = "body", key = "validated") {
  return (req, res, next) => {
    const target = req[source]
    const result = schema.safeParse(target)
    if (!result.success) {
      const { fieldErrors } = result.error.flatten()
      return res.status(400).json({
        error: "Geçersiz veri",
        details: fieldErrors,
      })
    }
    req[key] = result.data
    return next()
  }
}

module.exports = { validate }
