import type { ClientIds } from 'config/clients/types'

import { checkCookie } from 'helpers/cookie'

import { getApiUrl } from 'features/AuthServiceApp/config/routes'

const errorLexics = {
  1: 'error_invalid_email_or_password',
  2: 'error_missing_required_argument',
  3: 'error_unsupported_response_type',
  7: 'error_invalid_platform',
  8: 'error_failed_to_send_email',
  9: 'error_user_already_created',
}

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

type SuccessResponse = {
  ok: true,
}

export type UrlParams = {
  client_id: ClientIds,
  lang?: string,
  nonce?: string,
  redirect_uri: string,
  response_mode: string,
  response_type: string,
  scope?: string,
  state?: string,
}

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

export const registerCheck = async ({
  email,
  password,
  urlParams,
} : RegisterProps) => {
  const url = `
  ${getApiUrl('/registration')}${checkCookie('access_token')
  ? `&${checkCookie('access_token')}`
  : ''}`
  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])
}
