import { GOOGLE_CLIENT_ID, FACEBOOK_CLIENT_ID } from 'config'

import { getRandomString } from 'helpers'

import type { Settings } from 'features/AuthStore/helpers'

import { AuthProviders } from '../../config/authProviders'
import { PAGES } from '../../config/pages'

const getQueryString = (authProvider: AuthProviders, urlParams: Settings) => {
  switch (authProvider) {
    case AuthProviders.Google:
      return new URLSearchParams({
        client_id: GOOGLE_CLIENT_ID,
        nonce: urlParams.nonce || '0394852-3190485-2490358',
        redirect_uri: `${window.location.origin}${PAGES.oauth}`,
        response_type: 'token id_token',
        scope: 'openid email profile',
        state: urlParams.state || '',
      }).toString()

    case AuthProviders.Facebook:
      return new URLSearchParams({
        client_id: FACEBOOK_CLIENT_ID,
        code_challenge: getRandomString(43),
        nonce: urlParams.nonce || '0394852-3190485-2490358',
        redirect_uri: `${window.location.origin}${PAGES.oauth}`,
        response_type: 'id_token',
        scope: 'openid email public_profile',
        state: urlParams.state || '',
      }).toString()

    default:
      return ''
  }
}

export const getAuthUrl = (authProvider: AuthProviders, urlParams: Settings) => {
  const queryString = getQueryString(authProvider, urlParams)

  switch (authProvider) {
    case AuthProviders.Google:
      return `https://accounts.google.com/o/oauth2/v2/auth?${queryString}`

    case AuthProviders.Facebook:
      return `https://www.facebook.com/v11.0/dialog/oauth?${queryString}`

    default:
      return ''
  }
}
