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

export default class AmfBearer extends BearerAuthorization {
  /**
   * 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: 'bearer',
        valid: false,
        config: {
          token: '',
        } as IBearerAuthorization,
      }
    }
    return this.authorization
  }

  protected restoreValues(): void {
    const auth = this.ensureConfig()
    const { security } = this
    if (!security) {
      return
    }
    const restore = InputCache.get(this, security.id, true) as IBearerAuthorization | undefined
    if (!restore) {
      return
    }
    auth.config = restore
    this.requestUpdate()
  }

  protected override handleToken(e: Event): void {
    super.handleToken(e)
    const { security } = this
    if (!security) {
      return
    }
    const auth = this.ensureConfig()
    InputCache.set(this, security.id, auth.config, true)
  }
}
