import { html, fixture, assert, oneEvent, nextFrame, aTimeout } from '@open-wc/testing'
import { spy } from 'sinon'
import {
  EventTypes,
  IOAuth2Authorization,
  IRequestAuthorization,
  RequestAuthorizationKind,
} from '@api-client/core/browser.js'
import type OAuth2Authorization from '../../../src/elements/authorization/ui/OAuth2Authorization.js'
import type Input from '../../../src/md/input/Input.js'
import type UiButton from '../../../src/md/button/internals/button.js'
import '../../../src/define/authorization/oauth2-authorization.js'

describe('Authorization', () => {
  describe('<oauth2-authorization>', () => {
    describe('urn:ietf:params:oauth:grant-type:device_code', () => {
      const baseConfig: IOAuth2Authorization = {
        grantType: 'urn:ietf:params:oauth:grant-type:device_code',
        redirectUri: 'https://redirect.com/',
        clientId: 'test-client-id',
        clientSecret: 'test-secret-client',
        accessTokenUri: 'https://accounts.google.com/o/oauth2/v2/token',
        scopes: ['email', 'profile'],
        deviceCode: 'test-code',
      }

      async function basicFixture(opts: IOAuth2Authorization = {}): Promise<OAuth2Authorization> {
        const auth: IRequestAuthorization = {
          config: opts,
          enabled: true,
          kind: RequestAuthorizationKind,
          type: 'oauth 2',
          valid: true,
        }
        return fixture(html`<oauth2-authorization .authorization="${auth}"></oauth2-authorization>`)
      }

      async function baseUriFixture(baseUri: string, opts: IOAuth2Authorization): Promise<OAuth2Authorization> {
        const auth: IRequestAuthorization = {
          config: opts,
          enabled: true,
          kind: RequestAuthorizationKind,
          type: 'oauth 2',
          valid: true,
        }
        return fixture(
          html`<oauth2-authorization .authorization="${auth}" .baseUri="${baseUri}"></oauth2-authorization>`
        )
      }

      describe('DOM rendering', () => {
        let element: OAuth2Authorization
        let form: HTMLFormElement
        beforeEach(async () => {
          element = await basicFixture({ ...baseConfig })
          form = element.shadowRoot!.querySelector('form')!
        })

        it('has form in the DOM', async () => {
          assert.ok(form)
        })

        it(`has the clientId input`, async () => {
          const input = form.querySelector(`[name="clientId"]`) as Input
          assert.ok(input, 'has the input')
        })

        it(`has the clientSecret input`, async () => {
          const input = form.querySelector(`[name="clientSecret"]`) as Input
          assert.ok(input, 'has the input')
        })

        it(`has the accessTokenUri input`, async () => {
          const input = form.querySelector(`[name="accessTokenUri"]`) as Input
          assert.ok(input, 'has the input')
        })

        it('client secret is not required', async () => {
          const input = form.querySelector('[name="clientSecret"]') as Input
          assert.notOk(input.required)
        })

        it('does not render redirect URI filed', async () => {
          const node = element.shadowRoot!.querySelector('[name="redirectUri"]')
          assert.notOk(node)
        })

        it('does not render token section when no token information', () => {
          const node = element.shadowRoot!.querySelector('.current-token')
          assert.notOk(node)
        })

        it('renders token section when token information is set', async () => {
          element.config.accessToken = 'test-token'
          element.requestUpdate()
          await element.updateComplete
          const node = element.shadowRoot!.querySelector('.current-token')!
          assert.ok(node)
          const label = node.querySelector('.token-value')!
          assert.equal(label.textContent!.trim(), 'test-token')
        })
      })

      describe('Data initialization', () => {
        let element: OAuth2Authorization
        beforeEach(async () => {
          element = await basicFixture({ ...baseConfig })
        })

        it(`has the clientId`, async () => {
          const input = element.shadowRoot!.querySelector(`[name="clientId"]`) as Input
          assert.equal(input.value, baseConfig.clientId)
        })

        it(`has the clientSecret`, async () => {
          const input = element.shadowRoot!.querySelector(`[name="clientSecret"]`) as Input
          assert.equal(input.value, baseConfig.clientSecret)
        })

        it(`has the accessTokenUri input`, async () => {
          const input = element.shadowRoot!.querySelector(`[name="accessTokenUri"]`) as Input
          assert.equal(input.value, baseConfig.accessTokenUri)
        })

        it(`has the deviceCode input`, async () => {
          const input = element.shadowRoot!.querySelector(`[name="deviceCode"]`) as Input
          assert.equal(input.value, baseConfig.deviceCode)
        })
      })

      describe('Change notification', () => {
        let element: OAuth2Authorization
        beforeEach(async () => {
          element = await basicFixture({ ...baseConfig })
        })

        it(`notifies when clientId changes`, async () => {
          setTimeout(() => {
            const input = element.shadowRoot!.querySelector(`[name="clientId"]`) as Input
            input.value = 'changed'
            input.dispatchEvent(new CustomEvent('change'))
          })
          const e = await oneEvent(element, 'change')
          assert.ok(e)
        })

        it(`notifies when clientSecret changes`, async () => {
          setTimeout(() => {
            const input = element.shadowRoot!.querySelector(`[name="clientSecret"]`) as Input
            input.value = 'changed'
            input.dispatchEvent(new CustomEvent('change'))
          })
          const e = await oneEvent(element, 'change')
          assert.ok(e)
        })

        it(`notifies when accessTokenUri changes`, async () => {
          setTimeout(() => {
            const input = element.shadowRoot!.querySelector(`[name="accessTokenUri"]`) as Input
            input.value = 'changed'
            input.dispatchEvent(new CustomEvent('change'))
          })
          const e = await oneEvent(element, 'change')
          assert.ok(e)
        })

        it(`notifies when deviceCode changes`, async () => {
          setTimeout(() => {
            const input = element.shadowRoot!.querySelector(`[name="deviceCode"]`) as Input
            input.value = 'changed'
            input.dispatchEvent(new CustomEvent('change'))
          })
          const e = await oneEvent(element, 'change')
          assert.ok(e)
        })
      })

      describe('Data serialization', () => {
        let element: OAuth2Authorization
        beforeEach(async () => {
          element = await basicFixture({ ...baseConfig })
        })

        it(`serializes the clientId`, async () => {
          const result = element.serialize()
          assert.equal(result.clientId, baseConfig.clientId)
        })

        it(`serializes the clientSecret`, async () => {
          const result = element.serialize()
          assert.equal(result.clientSecret, baseConfig.clientSecret)
        })

        it(`serializes the accessTokenUri`, async () => {
          const result = element.serialize()
          assert.equal(result.accessTokenUri, baseConfig.accessTokenUri)
        })

        it(`serializes the scopes`, async () => {
          const result = element.serialize()
          assert.deepEqual(result.scopes, baseConfig.scopes)
        })

        it(`serializes the deviceCode`, async () => {
          const result = element.serialize()
          assert.deepEqual(result.deviceCode, baseConfig.deviceCode)
        })
      })

      describe('authorization event', () => {
        let element: OAuth2Authorization

        beforeEach(async () => {
          element = await basicFixture({ ...baseConfig })
        })

        async function sendResponse(
          state?: string,
          tokenType?: string,
          e?: CustomEvent<IOAuth2Authorization>
        ): Promise<IOAuth2Authorization> {
          await aTimeout(1)
          return {
            accessToken: 'test-token',
            tokenType,
            state: state || e!.detail.state,
          }
        }

        function mockTokenRequest(state?: string, tokenType?: string): void {
          window.addEventListener(EventTypes.Authorization.OAuth2.authorize, function f(e) {
            window.removeEventListener(EventTypes.Authorization.OAuth2.authorize, f)
            e.preventDefault()
            const typed = e as CustomEvent<IOAuth2Authorization & { result?: unknown }>
            typed.detail.result = sendResponse(state, tokenType, typed)
          })
        }

        function mockTokenErrorRequest(message?: string): void {
          window.addEventListener(EventTypes.Authorization.OAuth2.authorize, function f(e) {
            window.removeEventListener(EventTypes.Authorization.OAuth2.authorize, f)
            e.preventDefault()
            const typed = e as CustomEvent<IOAuth2Authorization & { result?: unknown }>
            typed.detail.result = Promise.reject(new Error(message))
          })
        }

        it(`sets the serialized values onto the event`, async () => {
          const handler = spy()
          element.addEventListener(EventTypes.Authorization.OAuth2.authorize, handler)
          element.authorize()
          const { detail } = handler.args[0][0] as CustomEvent<IOAuth2Authorization & { result?: unknown }>
          delete detail.state
          delete detail.result
          assert.deepEqual(detail, element.serialize())
        })

        it('calls authorize() from button click', () => {
          const button = element.shadowRoot!.querySelector('.auth-button') as UiButton
          const handler = spy()
          element.addEventListener(EventTypes.Authorization.OAuth2.authorize, handler)
          button.click()
          assert.isTrue(handler.called)
        })

        it('sets the #authorizing flag', async () => {
          mockTokenRequest()
          const button = element.shadowRoot!.querySelector('.auth-button') as UiButton
          button.click()
          assert.isTrue(element.authorizing)
        })

        it('ignores authorization when did not pass validation', async () => {
          element.config.deviceCode = ''
          element.requestUpdate()
          await element.updateComplete
          element.authorize()
          assert.isFalse(element.authorizing)
        })

        it('resets the #authorizing flag when token response', async () => {
          mockTokenRequest()
          element.authorize()
          await aTimeout(2)
          await nextFrame()
          assert.isFalse(element.authorizing)
        })

        it('sets state on the event', async () => {
          const handler = spy()
          element.addEventListener(EventTypes.Authorization.OAuth2.authorize, handler)
          element.authorize()
          const { detail } = handler.args[0][0] as CustomEvent<IOAuth2Authorization & { result?: unknown }>
          const eventState = detail.state
          assert.typeOf(eventState, 'string', 'event state is set')
        })

        it('sets values from the response event with state', async () => {
          mockTokenRequest(undefined, 'other')
          element.authorize()
          await aTimeout(2)
          await nextFrame()
          assert.equal(element.config.accessToken, 'test-token')
          assert.equal(element.config.tokenType, 'other')
        })

        it('sets "lastErrorMessage" with event message', async () => {
          const message = 'Test error'
          mockTokenErrorRequest(message)
          await nextFrame()
          try {
            await element.authorize()
          } catch {
            // ..
          }
          await nextFrame()
          assert.equal(element.lastErrorMessage, message)
        })

        it('renders error message', async () => {
          mockTokenErrorRequest('This is an error')
          try {
            await element.authorize()
          } catch {
            // ...
          }
          await nextFrame()
          const node = element.shadowRoot!.querySelector('.error-message')
          assert.ok(node)
        })

        it('clears "lastErrorMessage" when requesting the token again', async () => {
          mockTokenErrorRequest('This is an error')
          try {
            await element.authorize()
          } catch {
            // ...
          }
          await nextFrame()
          await element.authorize()
          assert.isUndefined(element.lastErrorMessage)
        })
      })

      describe('#baseUri', () => {
        const baseUri = 'https://api.domain.com/auth'

        it('adds base URI to accessTokenUri', async () => {
          const params = { ...baseConfig }
          params.accessTokenUri = '/authorize'
          const element = await baseUriFixture(baseUri, params)
          await nextFrame()
          const result = element.serialize()
          assert.equal(result.accessTokenUri, 'https://api.domain.com/auth/authorize')
        })
      })

      describe('a11y', () => {
        let element: OAuth2Authorization

        beforeEach(async () => {
          element = await basicFixture({ ...baseConfig })
        })

        it('passes automated a11y tests', async () => {
          await assert.isAccessible(element)
        })
      })
    })
  })
})
