import type { User } from 'oidc-client'
import { createOidcAuth, SignInType, type OidcAuth, LogLevel } from 'vue-oidc-client/vue3'
import { getConfig } from './siteConfig'
import type { Config } from '@/types/Config'

const loco = window.location
const appRootUrl = `${loco.protocol}//${loco.host}${import.meta.env.BASE_URL}`

let authObj = null as OidcAuth | null

export async function configureOidc() {
  if (authObj) return Promise.resolve(authObj)
  const appConfig: Config = await getConfig().then((c) => {
    if (c === null) {
      throw new Error("config was null")
    }
    return c
  }).catch((reason) => {
    console.log(reason)
    throw new Error(reason);
  })
  
  const config = {
    authority: appConfig.oidcAuthority,
    client_id: appConfig.oidcClientID,
    response_type: 'code',
    scope: 'openid profile email api offline_access'
  }

  authObj = createOidcAuth(
    'main',
    SignInType.Window,
    appRootUrl,
    {
      ...config,
      // test use
      prompt: 'login'
    },
    console,
    LogLevel.Debug
  )

  // handle events
  authObj.events.addAccessTokenExpiring(function () {
    // eslint-disable-next-line no-console
    console.log('access token expiring')
  })

  authObj.events.addAccessTokenExpired(function () {
    // eslint-disable-next-line no-console
    console.log('access token expired')
  })

  authObj.events.addSilentRenewError(function (err: Error) {
    // eslint-disable-next-line no-console
    console.error('silent renew error', err)
  })

  authObj.events.addUserLoaded(function (user: User) {
    // eslint-disable-next-line no-console
    console.log('user loaded', user)
  })

  authObj.events.addUserUnloaded(function () {
    // eslint-disable-next-line no-console
    console.log('user unloaded')
  })

  authObj.events.addUserSignedOut(function () {
    // eslint-disable-next-line no-console
    console.log('user signed out')
  })

  authObj.events.addUserSessionChanged(function () {
    // eslint-disable-next-line no-console
    console.log('user session changed')
  })

  return authObj
}
