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.instat'
    case ClientNames.Facr:
      return ClientNames.Facr
    case ClientNames.Instat:
      return ClientNames.Instat
    default:
      return ClientNames.Insports
  }
}

const redirectUrl = () => {
  const clientName = getClientNameByRedirectUri()
  switch (true) {
    case (process.env.NODE_ENV === 'development' || client.name === 'lff' || client.name === 'facr'):
      return `${window.origin}/redirect`
    case (ENV === 'staging' || ENV === 'preproduction'):
      return `https://${stageENV}.insports.tv/redirect`
    default:
      return `https://${clientName}.tv/redirect`
  }
}

export const getClientSettings = (): Settings => ({
  authority: AUTH_SERVICE,
  automaticSilentRenew: true,
  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 === 'instat' || client.name === 'insports'
