import {
  type IRequestAuthorization,
  Kind as RequestAuthorizationKind,
} from '@api-client/core/models/RequestAuthorization.js'
import { PropertyValues } from 'lit'
import { property } from 'lit/decorators.js'
import OidcAuthorization from '../../authorization/ui/OidcAuthorization.js'
import type { IOidcAuthorization } from '@api-client/core/models/Authorization.js'
import type {
  IApiParametrizedSecurityScheme,
  IApiSecurityOpenIdConnectSettings,
} from '@api-client/core/amf/definitions/Api.js'

export default class AmfOidc extends OidcAuthorization {
  /**
   * The in-memory key where the values are stored.
   */
  @property({ type: Object }) accessor security: IApiParametrizedSecurityScheme | undefined

  protected override willUpdate(cp: PropertyValues<this>): void {
    if (cp.has('security')) {
      this.restoreValues()
    }
    super.willUpdate(cp)
  }

  protected ensureConfig(): IRequestAuthorization {
    if (!this.authorization) {
      this.authorization = {
        enabled: true,
        kind: RequestAuthorizationKind,
        type: 'oauth 2',
        valid: false,
        config: {} as IOidcAuthorization,
      }
    }
    return this.authorization
  }

  protected restoreValues(): void {
    const { security } = this
    this.authorization = undefined
    const auth = this.ensureConfig()

    if (!security) {
      return
    }

    const { scheme } = security
    if (!scheme) {
      return
    }
    const settings = scheme.settings as IApiSecurityOpenIdConnectSettings | undefined
    if (!settings) {
      return
    }
    const { url } = settings
    const cnf = auth.config as IOidcAuthorization
    cnf.issuerUri = url
    if (url) {
      this.discover()
    }
    auth.config = this.serialize()
    this.notifyChange()
  }
}
