import { property } from 'lit/decorators.js'
import { EventTypes as CoreEventTypes } from '@api-client/core/events/EventTypes.js'
import type { IOAuth2Authorization, IOidcTokenError, IOidcTokenInfo } from '@api-client/core/models/Authorization.js'
import type { ContextEvent } from '@api-client/core/events/BaseEvents.js'
import type { OauthProcessingOptions } from '@api-client/core/authorization/types.js'
import { OidcAuthorization } from '@api-client/core/authorization/OidcAuthorization.js'
import ApiElement from '../ApiElement.js'

export const authorizeHandler = Symbol('authorizeHandler')

export default class OidcAuthorize extends ApiElement {
  /**
   * When set it uses this value to prefix the call to the
   * OAuth 2 token endpoint. This is to support use cases when
   * the requests should be proxied through a server to avoid CORS problems.
   * @attribute
   */
  @property({ type: String }) accessor tokenProxy: string | undefined

  /**
   * When set it encodes the token URI value before adding it to the
   * `tokenProxy`. This is to be used when the proxy takes the target
   * URL as a query parameter.
   * @attribute
   */
  @property({ type: String }) accessor tokenProxyEncode: boolean | undefined

  constructor() {
    super()
    this[authorizeHandler] = this[authorizeHandler].bind(this)
  }

  override connectedCallback(): void {
    super.connectedCallback()
    this.eventsTarget.addEventListener(CoreEventTypes.Authorization.Oidc.authorize, this[authorizeHandler])
    this.setAttribute('aria-hidden', 'true')
  }

  override disconnectedCallback(): void {
    super.disconnectedCallback()
    this.eventsTarget.removeEventListener(CoreEventTypes.Authorization.Oidc.authorize, this[authorizeHandler])
  }

  [authorizeHandler](event: Event): void {
    const e = event as ContextEvent<IOAuth2Authorization, (IOidcTokenInfo | IOidcTokenError)[]>
    const config = { ...e.detail } as IOAuth2Authorization
    e.detail.result = this.authorize(config)
  }

  /**
   * Authorize the user using provided settings.
   * This is left for compatibility. Use the `OAuth2Authorization` instead.
   *
   * @param settings The authorization configuration.
   */
  async authorize(settings: IOAuth2Authorization): Promise<(IOidcTokenInfo | IOidcTokenError)[]> {
    const { tokenProxy, tokenProxyEncode } = this
    const options: OauthProcessingOptions = {}
    if (tokenProxy && typeof tokenProxy === 'string') {
      options.tokenProxy = tokenProxy
    }
    if (tokenProxy && tokenProxyEncode && typeof tokenProxyEncode === 'boolean') {
      options.tokenProxyEncode = tokenProxyEncode
    }
    const auth = new OidcAuthorization(settings, options)
    auth.checkConfig()
    // FIXME: Fix the typings in the `OidcAuthorization` class.
    return auth.authorize() as unknown as (IOidcTokenInfo | IOidcTokenError)[]
  }
}
