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

const proc = PROCEDURES.create_user

const responseStatus = {
  FAILURE: 2,
  SUCCESS: 1,
}

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

type Args = {
  address1: string,
  address2?: string,
  city?: string,
  cityId?: number,
  countryId: number,
  email: string,
  firstname: string,
  lastname: string,
  password: string,
  phone: string,
  postalCode: number,
  region: string,
}

export const register = async ({
  address1,
  address2,
  city,
  cityId,
  countryId,
  email,
  firstname,
  lastname,
  password,
  phone,
  postalCode,
  region,
}: Args) => {
  const config = {
    body: {
      params: {
        _p_address_line1: address1,
        _p_address_line2: address2,
        _p_city: city,
        _p_city_id: cityId,
        _p_country_id: countryId,
        _p_email: email,
        _p_firstname: firstname,
        _p_lastname: lastname,
        _p_password: password,
        _p_phone: phone,
        _p_postal_code: postalCode,
        _p_region: region,
      },
      proc,
    },
  }

  const response: Response = await callApi({
    config,
    url: DATA_URL,
  })

  if (response._p_status === responseStatus.SUCCESS) {
    return Promise.resolve(response)
  }

  return Promise.reject(response._p_error)
}
