import type { UserManagerSettings } from 'oidc-client'
import { WebStorageStateStore } from 'oidc-client'

import { client } from 'config/clients'
import { AUTH_SERVICE } from 'config/routes'
import { ClientIds, ClientNames } from 'config/clients/types'
import { ENV, stageENV } from 'config/env'

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

export interface Settings extends UserManagerSettings {
  client_id: ClientIds,
  lang?: string,
  nonce?: string,
  redirect_uri: string,
  response_mode: string,
  response_type: string,
  scope?: string,
  state?: string,
}

export const getClientNameByRedirectUri = () => {
  switch (client.name) {
    case ClientNames.Lff:
      return 'lff.insports'
    case ClientNames.India:
      return 'india.insports'
    case ClientNames.Tunisia:
      return 'diwan.insports'
    case ClientNames.Fqtv:
      return 'fqtv.insports'
    case ClientNames.Facr:
      return ClientNames.Facr
    case ClientNames.Instat:
      return ClientNames.Instat
    default:
      return ClientNames.Insports
  }
}

const clientsForRedirect = {
  facr: ClientNames.Facr,
  fqtv: ClientNames.Fqtv,
  india: ClientNames.India,
  lff: ClientNames.Lff,
  tunisia: ClientNames.Tunisia,
}

const redirectUrl = () => {
  const clientName = getClientNameByRedirectUri()
  switch (true) {
    case (
      process.env.NODE_ENV === 'development'
        // @ts-ignore
        || Boolean(clientsForRedirect[client.name])
    ):
      return `${window.origin}`
    case (ENV === 'staging' || ENV === 'preproduction'):
      return `https://${stageENV}.insports.tv`
    default:
      return `https://${clientName}.tv`
  }
}

export const getClientSettings = (): Settings => ({
  authority: AUTH_SERVICE,
  client_id: client.auth.clientId,
  filterProtocolClaims: false,
  loadUserInfo: false,
  metadataUrl: `${API_ROOT}/.well-known/openid-configuration${client.auth.metaDataUrlParams || ''}`,
  redirect_uri: redirectUrl(),
  response_mode: 'query',
  response_type: 'id_token token',
  scope: 'openid',
  silent_redirect_uri: `${window.location.origin ?? window.origin}/silent-refresh.html`,
  userStore: new WebStorageStateStore({ store: window.localStorage }),
})

export const needCheckNewDeviсe = client.name === ClientNames.Instat
  || client.name === ClientNames.Insports
  || client.name === ClientNames.India
