import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mountPasskeyLogin, type PasskeyAuthApi } from '../src/login-passkey'
import { WebAuthnError, type AuthenticationResult, type WebAuthnClient } from '../src/webauthn'
import type { ApiClient } from '../src/api-client'

const fakeAssertion: AuthenticationResult = {
  id: 'x',
  rawId: 'cmF3',
  type: 'public-key',
  response: { clientDataJSON: 'Y2Q', authenticatorData: 'YWQ', signature: 'c2ln', userHandle: null },
}

function reqOptions(rpId: string): PublicKeyCredentialRequestOptions {
  return { challenge: new Uint8Array([1]).buffer, rpId } as PublicKeyCredentialRequestOptions
}

const stubApi = {} as ApiClient

describe('mountPasskeyLogin (T7)', () => {
  let root: HTMLElement
  beforeEach(() => {
    root = document.createElement('div')
    document.body.append(root)
  })

  it('successful authenticate → assertion verified → "ok"', async () => {
    const wa: WebAuthnClient = { register: vi.fn(), authenticate: vi.fn(async () => fakeAssertion) }
    const authApi: PasskeyAuthApi = {
      getLoginChallenge: vi.fn(async () => reqOptions('app.example.com')),
      verifyLogin: vi.fn(async () => 'ok' as const),
      getStepUpChallenge: vi.fn(),
      verifyStepUp: vi.fn(),
    }
    const login = mountPasskeyLogin(root, stubApi, wa, authApi)
    await expect(login.login()).resolves.toBe('ok')
    expect(authApi.verifyLogin).toHaveBeenCalledWith(fakeAssertion)
  })

  it('user cancels the passkey prompt → "rejected", no session, no throw leak', async () => {
    const wa: WebAuthnClient = {
      register: vi.fn(),
      authenticate: vi.fn(async () => {
        throw new WebAuthnError('cancelled', 'dismissed')
      }),
    }
    const authApi: PasskeyAuthApi = {
      getLoginChallenge: vi.fn(async () => reqOptions('app.example.com')),
      verifyLogin: vi.fn(async () => 'ok' as const),
      getStepUpChallenge: vi.fn(),
      verifyStepUp: vi.fn(),
    }
    const login = mountPasskeyLogin(root, stubApi, wa, authApi)
    await expect(login.login()).resolves.toBe('rejected')
    expect(authApi.verifyLogin).not.toHaveBeenCalled()
  })

  it('stepUp runs a FRESH ceremony each call (a stolen cookie alone cannot open a session)', async () => {
    const authenticate = vi.fn(async () => fakeAssertion)
    const wa: WebAuthnClient = { register: vi.fn(), authenticate }
    const authApi: PasskeyAuthApi = {
      getLoginChallenge: vi.fn(),
      verifyLogin: vi.fn(),
      getStepUpChallenge: vi.fn(async () => reqOptions('app.example.com')),
      verifyStepUp: vi.fn(async () => 'ok' as const),
    }
    const login = mountPasskeyLogin(root, stubApi, wa, authApi)
    await login.stepUp('h1')
    await login.stepUp('h1')
    expect(authenticate).toHaveBeenCalledTimes(2) // not cached — a new assertion every time
  })

  it('rpId comes from the SERVER challenge, never location.hostname (§8 Q#5)', async () => {
    const authenticate = vi.fn((_c: PublicKeyCredentialRequestOptions) => Promise.resolve(fakeAssertion))
    const wa: WebAuthnClient = { register: vi.fn(), authenticate }
    const authApi: PasskeyAuthApi = {
      getLoginChallenge: vi.fn(async () => reqOptions('app.example.com')),
      verifyLogin: vi.fn(async () => 'ok' as const),
      getStepUpChallenge: vi.fn(),
      verifyStepUp: vi.fn(),
    }
    const login = mountPasskeyLogin(root, stubApi, wa, authApi)
    await login.login()
    const passed = authenticate.mock.calls[0]![0] as PublicKeyCredentialRequestOptions
    expect(passed.rpId).toBe('app.example.com')
    expect(passed.rpId).not.toBe(window.location.hostname)
  })

  it('a failed challenge fetch → "rejected" with an error message (no throw leak)', async () => {
    const wa: WebAuthnClient = { register: vi.fn(), authenticate: vi.fn(async () => fakeAssertion) }
    const authApi: PasskeyAuthApi = {
      getLoginChallenge: vi.fn(async () => {
        throw new Error('challenge 500')
      }),
      verifyLogin: vi.fn(),
      getStepUpChallenge: vi.fn(),
      verifyStepUp: vi.fn(),
    }
    const login = mountPasskeyLogin(root, stubApi, wa, authApi)
    await expect(login.login()).resolves.toBe('rejected')
    expect(root.querySelector('.passkey-error')?.textContent).toContain('Could not start')
  })

  it('a non-cancel authenticate failure → "rejected" and a failure message', async () => {
    const wa: WebAuthnClient = {
      register: vi.fn(),
      authenticate: vi.fn(async () => {
        throw new Error('authenticator exploded')
      }),
    }
    const authApi: PasskeyAuthApi = {
      getLoginChallenge: vi.fn(async () => reqOptions('app.example.com')),
      verifyLogin: vi.fn(),
      getStepUpChallenge: vi.fn(),
      verifyStepUp: vi.fn(),
    }
    const login = mountPasskeyLogin(root, stubApi, wa, authApi)
    await expect(login.login()).resolves.toBe('rejected')
    expect(root.querySelector('.passkey-error')?.textContent).toContain('failed')
  })

  it('exposes EXACTLY login + stepUp — no phone/SMS/OTP field (never SMS)', () => {
    const wa: WebAuthnClient = { register: vi.fn(), authenticate: vi.fn() }
    const authApi = {
      getLoginChallenge: vi.fn(),
      verifyLogin: vi.fn(),
      getStepUpChallenge: vi.fn(),
      verifyStepUp: vi.fn(),
    } as unknown as PasskeyAuthApi
    const login = mountPasskeyLogin(root, stubApi, wa, authApi)
    expect(Object.keys(login).sort()).toEqual(['login', 'stepUp'])
    expect(JSON.stringify(Object.keys(login))).not.toMatch(/sms|phone|otp/i)
  })
})
