import {
  DATA_URL,
  PROCEDURES,
  TOKEN_KEY,
} from 'config'
import { callApiBase } from 'helpers/callApi'
import { checkStatus } from 'helpers/callApi/checkStatus'
import { parseJSON } from 'helpers/callApi/parseJSON'

const proc = PROCEDURES.auth_user

const statusCodes = {
  ACCOUNT_EXPIRED: 5,
  EMAIL_NOT_FOUND: 2,
  INVALID_CREDENTIALS: 3,
  SUCCESS: 1,
  USER_REMOVED_OR_BLOCKED: 4,
} as const

type StatusCodes = typeof statusCodes[keyof typeof statusCodes]

type Response = {
  _p_status: StatusCodes,
}

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

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

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

    const token = response.headers.get(TOKEN_KEY)
    const { _p_status }: Response = await parseJSON(response)

    if (token && _p_status === statusCodes.SUCCESS) {
      return Promise.resolve(token)
    }
    return Promise.reject(_p_status)
  } catch (error) {
    return Promise.reject()
  }
}
