import { beforeEach, describe, expect, it, vi } from 'vitest'

const mockEnsureSuperTokensInit = vi.fn()
const mockRender = vi.fn()
const mockCreateRoot = vi.fn((_: Element | DocumentFragment | null) => ({
  render: mockRender,
}))

vi.mock('../auth/supertokens-client', () => ({
  ensureSuperTokensInit: () => mockEnsureSuperTokensInit(),
}))

vi.mock('../App', () => ({
  default: () => null,
}))

vi.mock('react-dom/client', () => ({
  default: {
    createRoot: (element: Element | DocumentFragment | null) => mockCreateRoot(element),
  },
}))

describe('main bootstrap', () => {
  beforeEach(() => {
    vi.resetModules()
    mockEnsureSuperTokensInit.mockReset()
    mockCreateRoot.mockClear()
    mockRender.mockClear()
    document.body.innerHTML = '<div id="root"><div id="hypertwist-initial-shell">Boot</div></div>'
  })

  it('initializes shared auth before creating the React root', async () => {
    await import('../main')
    await Promise.resolve()

    const root = document.getElementById('root')

    expect(mockEnsureSuperTokensInit).toHaveBeenCalledTimes(1)
    expect(mockCreateRoot).toHaveBeenCalledWith(root)
    expect(mockRender).toHaveBeenCalledTimes(1)
    expect(mockEnsureSuperTokensInit.mock.invocationCallOrder[0]).toBeLessThan(
      mockCreateRoot.mock.invocationCallOrder[0],
    )
  })
})
