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

import type { UrlParams } from './register'

const errorLexics = {
  1: 'error_invalid_email_or_password',
  4: 'error_user_not_found',
  11: 'error_user_not_confirm',
}

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

type SuccessResponse = {
  ok: true,
}

type LoginProps = {
  email: string,
  password: string,
  urlParams: UrlParams,
}

export const loginCheck = async ({
  email,
  password,
  urlParams,
}: LoginProps) => {
  const url = getApiUrl('/authorize-check')

  const init: RequestInit = {
    body: new URLSearchParams({
      email,
      password,
      ...urlParams,
    }),
    method: 'POST',
  }
  const response = await fetch(url, init)

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

  if (body.ok) return Promise.resolve()

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