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

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

import type { Languages } from 'config/languages'

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

const redirectUrl = () => {
  if (process.env.NODE_ENV === 'development') {
    return `${window.origin}/redirect`
  }
  if (ENV === 'staging') {
    return `https://${stageENV}.instat.tv/redirect`
  }
  return `https://${client.name}.tv/redirect`
}

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