import { DATA_URL, PROCEDURES } from 'config'
import { callApiBase } from 'helpers'

const proc = PROCEDURES.create_user

const statusCodes = {
  EMAIL_IN_USE: 2,
  SUCCESS: 1,
}

const errorMessages = {
  [statusCodes.EMAIL_IN_USE]: 'error_email_already_in_use',
}

type Response = {
  _p_error: string | null,
  _p_status: 1 | 2,
}

type Args = {
  email: string,
  password: string,
}

export const register = async ({
  email,
  password,
}: Args) => {
  const config = {
    body: {
      params: {
        _p_email: email,
        _p_password: password,
      },
      proc,
    },
  }

  try {
    const response = await callApiBase({
      config,
      url: DATA_URL,
    })

    const { _p_status }: Response = await response.json()

    if (_p_status === statusCodes.SUCCESS) {
      return Promise.resolve(response)
    }
    return Promise.reject(errorMessages[_p_status])
  } catch {
    return Promise.reject()
  }
}
