import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'

// Mock qrcode before any imports — avoids canvas rendering in happy-dom
vi.mock('qrcode', () => ({
  default: {
    toDataURL: vi.fn().mockResolvedValue('data:image/png;base64,fakeqr'),
  },
}))

// Mock API client
vi.mock('../../../api/client.js', () => ({
  totpSetup: vi.fn().mockResolvedValue({
    provisioning_uri: 'otpauth://totp/DocuVault:test@example.com?secret=JBSWY3DPEHPK3PXP',
    secret: 'JBSWY3DPEHPK3PXP',
  }),
  totpEnable: vi.fn(),
}))

import TotpEnrollment from '../TotpEnrollment.vue'

beforeEach(() => {
  setActivePinia(createPinia())
  vi.clearAllMocks()
})

describe('TotpEnrollment — QR code rendering (AUTH-03)', () => {
  it('renders an <img> tag with a data:image/ src after startSetup, not an otpauth:// link', async () => {
    const wrapper = mount(TotpEnrollment, {
      global: {
        plugins: [createPinia()],
        stubs: {
          AppSpinner: { template: '<span />' },
          BackupCodesDisplay: { template: '<div />', props: ['codes'] },
        },
      },
    })

    // Initial state — verify step not shown yet
    expect(wrapper.find('img').exists()).toBe(false)

    // Find and click the setup button
    const setupButton = wrapper.find('button')
    expect(setupButton.exists()).toBe(true)
    expect(setupButton.text()).toContain('Set up two-factor authentication')
    await setupButton.trigger('click')

    // Wait for all async operations (totpSetup + QRCode.toDataURL)
    await flushPromises()

    // Assert: <img> must exist with a data:image/ src
    const img = wrapper.find('img')
    expect(img.exists()).toBe(true)
    expect(img.attributes('src')).toMatch(/^data:image\//)

    // Assert: no <a> tag with href starting with otpauth:// (the old link-based approach)
    const links = wrapper.findAll('a')
    const otpauthLinks = links.filter(a =>
      (a.attributes('href') || '').startsWith('otpauth://')
    )
    expect(otpauthLinks).toHaveLength(0)
  })

  it('displays the manual secret key after startSetup', async () => {
    const wrapper = mount(TotpEnrollment, {
      global: {
        plugins: [createPinia()],
        stubs: {
          AppSpinner: { template: '<span />' },
          BackupCodesDisplay: { template: '<div />', props: ['codes'] },
        },
      },
    })

    await wrapper.find('button').trigger('click')
    await flushPromises()

    // The secret JBSWY3DPEHPK3PXP must appear in the rendered output
    expect(wrapper.text()).toContain('JBSWY3DPEHPK3PXP')
  })
})
