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

const proc = PROCEDURES.save_user_info

export type SaveUserInfo = {
  address_line1: string | null,
  address_line2: string | null,
  city: string | null,
  cityId: number | null,
  countryId: number | null,
  firstname: string | null,
  isUnsubscribed: boolean | null,
  language_id: number | null,
  lastname: string | null,
  phone: string | null,
  postalCode: number | null,
  region: string | null,
}

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

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

export const saveUserInfo = async ({
  address_line1,
  address_line2,
  city,
  cityId,
  countryId,
  firstname,
  isUnsubscribed,
  language_id,
  lastname,
  phone,
  postalCode,
  region,
}: SaveUserInfo) => {
  const config = {
    body: {
      params: {
        _p_address_line1: address_line1,
        _p_address_line2: address_line2,
        _p_city: city,
        _p_city_id: cityId,
        _p_country_id: countryId,
        _p_firstname: firstname,
        _p_is_unsubscribed: isUnsubscribed,
        _p_language_id: language_id,
        _p_lastname: lastname,
        _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)
}
