import { html, TemplateResult } from 'lit'
import { property } from 'lit/decorators.js'
import { ApiDocumentationBase } from './ApiDocumentationBase.js'
import { Events } from '../../events/amf/Events.js'
import '../../define/amf/api-parametrized-security-scheme.js'
import type { IApiSecurityRequirement } from '@api-client/core/amf/definitions/Api.js'

export default class ApiSecurityRequirementDocument extends ApiDocumentationBase {
  protected securityRequirementValue?: IApiSecurityRequirement

  get securityRequirement(): IApiSecurityRequirement | undefined {
    return this.securityRequirementValue
  }

  @property({ type: Object })
  set securityRequirement(value: IApiSecurityRequirement | undefined) {
    const old = this.securityRequirementValue
    if (old === value) {
      return
    }
    this.securityRequirementValue = value
    this.processGraph()
  }

  override async processGraph(): Promise<void> {
    await this.querySecurity()
    this.requestUpdate()
  }

  /**
   * Queries for the security requirements object.
   */
  async querySecurity(): Promise<void> {
    const { domainId } = this
    if (!domainId) {
      // this[securityValue] = undefined;
      return
    }
    if (this.securityRequirementValue && this.securityRequirementValue.id === domainId) {
      // in case the security model was provided via the property setter.
      return
    }
    try {
      const info = await Events.Security.getRequirement(this, domainId)
      this.securityRequirementValue = info
    } catch (e) {
      const ex = e as Error
      this.securityRequirementValue = undefined
      Events.Telemetry.exception(this, ex.message, false)
      Events.Reporting.error(this, ex, `Unable to query for API operation data: ${ex.message}`, this.localName)
    }
  }

  override render(): TemplateResult {
    const scheme = this.securityRequirementValue
    if (!scheme || !scheme.schemes || !scheme.schemes.length) {
      return html``
    }
    return html`
      <div class="security-requirements">
        ${scheme.schemes.map(
          (item) =>
            html` <api-parametrized-security-scheme
              .securityScheme="${item.scheme}"
              .settings="${item.settings}"
              settingsOpened
            ></api-parametrized-security-scheme>`
        )}
      </div>
    `
  }
}
