import { setupWorker, rest } from "msw"

const createError = (field, message) => ({
  field,
  message,
})

const validate = (form, data) => {
  const errors = []

  switch (form) {
    case "people": {
      const { first_name } = data

      if (first_name.length < 5) {
        errors.push(
          createError("first_name", "must be greater than 4 characters")
        )
      }
    }
  }

  return errors
}

export const worker = setupWorker(
  rest.post("/submit", (req, res, ctx) => {
    return res(ctx.json({}))
  }),
  rest.post("/people", (req, res, ctx) => {
    const errors = validate("people", req.body)

    return res(ctx.json({ errors }))
  }),
  rest.post("/validations", (req, res, ctx) => {
    const { first_name } = req.body.validation_data

    if (first_name.length < 5) {
      return res(
        ctx.json(validate(req.body.validation_type, req.body.validation_data))
      )
    }

    return res(ctx.json([]))
  })
)
