import { getApiUrl } from '../config/routes'

const errorLexics = {
  5: '',
  10: '',
}

type FailedResponse = {
  error: {
    code: keyof typeof errorLexics,
    message?: string,
  },
  ok: false,
}

type SuccessResponse = {
  data: {
    url: string,
  },
  ok: true,
}

export const changePassword = async (password: string) => {
  const url = getApiUrl('/change_password')
  const init: RequestInit = {
    body: new URLSearchParams({
      password,
    }),
    method: 'PUT',
  }
  const response = await fetch(url, init)

  const body: SuccessResponse | FailedResponse = await response.json()

  if (body.ok) return body.data.url

  return Promise.reject(errorLexics[body.error.code])
}
