import api from 'src/api'

export const createReview = async (reviewData) => {
  const { photos, ...rest } = reviewData

  if (photos && photos.length > 0) {
    const form = new FormData()

    Object.entries(rest).forEach(([key, val]) => {
      if (val === null || val === undefined) return
      if (Array.isArray(val)) val.forEach(v => form.append(`${key}[]`, v))
      else if (typeof val === 'boolean') form.append(key, val ? '1' : '0')
      else form.append(key, val)
    })

    photos.forEach(file => form.append('photos[]', file))

    const { data } = await api.post('/reviews', form)

    return data.payload
  }

  const { data } = await api.post('/reviews', rest)

  return data.payload
}

export const getImprovementTypes = async (origin = 'both') => {
  const { data } = await api.get('/improvement-types', { params: { origin } })
  return data.payload
}
