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

const errorLexics = {
  8: 'error_failed_to_send_email',
  15: 'error_email_field_required',
  18: 'error_user_is_already_verified',
  19: 'error_no_more_than_one_email_per_minute',
}

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 TResendConfirmation = {
  email: string,
  urlParams: UrlParams,
}

export const resendConfirmation = async ({
  email,
  urlParams,
} : TResendConfirmation) => {
  const url = getAuthApiUrl('/repeat_confirm_email')
  const init: RequestInit = {
    body: new URLSearchParams({
      email,
      ...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])
}
