import { fixture, assert, html, aTimeout } from '@open-wc/testing'
import { ApiDefinitions, AmfDefinitions } from '@api-client/core/browser.js'
import { AmfLoader } from '../AmfLoader.js'
import { DomEventsAmfStore } from '../../../src/amf/store/DomEventsAmfStore.js'
import ApiSecurityRequirementDocumentElement from '../../../src/elements/amf/ApiSecurityRequirementDocument.element.js'
import '../../../src/define/amf/api-security-requirement-document.js'

describe('ApiSecurityRequirementDocumentElement', () => {
  const loader = new AmfLoader()
  const store = new DomEventsAmfStore(window)
  store.listen()

  async function domainIdFixture(domainId?: string): Promise<ApiSecurityRequirementDocumentElement> {
    const element = (await fixture(
      html`<api-security-requirement-document
        .queryDebouncerTimeout="${0}"
        .domainId="${domainId}"
      ></api-security-requirement-document>`
    )) as ApiSecurityRequirementDocumentElement
    await aTimeout(0)
    return element
  }

  async function modelFixture(
    model?: ApiDefinitions.IApiSecurityRequirement
  ): Promise<ApiSecurityRequirementDocumentElement> {
    const element = (await fixture(
      html`<api-security-requirement-document
        .queryDebouncerTimeout="${0}"
        .securityRequirement="${model}"
      ></api-security-requirement-document>`
    )) as ApiSecurityRequirementDocumentElement
    await aTimeout(0)
    return element
  }

  let model: AmfDefinitions.IAmfDocument
  before(async () => {
    model = await loader.getGraph('secured-api')
    store.amf = model
  })

  it('finds the security for an operation', async () => {
    const op = loader.getOperation(model, '/custom1', 'get')
    const [security] = op.security
    const { id } = security
    const element = await domainIdFixture(id)
    assert.deepEqual(element.securityRequirement, security)
  })

  it('renders the security requirement when passing a serialized model', async () => {
    const op = loader.getOperation(model, '/custom1', 'get')
    const [security] = op.security
    const element = await modelFixture(security)
    const node = element.shadowRoot!.querySelector('api-parametrized-security-scheme')
    assert.ok(node, 'has the documentation element node')
  })
})
