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

import { buildSuperTokensApiVersionUrl, probeSuperTokensCoreHealth } from '../auth-health'

describe('buildSuperTokensApiVersionUrl', () => {
  it('preserves a configured core path prefix and appends the API-version route', () => {
    const result = buildSuperTokensApiVersionUrl({
      connectionUri: 'http://localhost:3567/core',
      apiDomain: 'http://localhost:3001',
      websiteDomain: 'http://localhost:4273',
    })

    expect(result).toBe('http://localhost:3567/core/apiversion?apiDomain=http%3A%2F%2Flocalhost%3A3001&websiteDomain=http%3A%2F%2Flocalhost%3A4273')
  })
})

describe('probeSuperTokensCoreHealth', () => {
  it('reports ready when the core responds with supported versions', async () => {
    const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(
      new Response(JSON.stringify({
        versions: ['2.7', '2.21', '5.0'],
      }), {
        status: 200,
        headers: {
          'content-type': 'application/json',
        },
      }),
    )

    await expect(probeSuperTokensCoreHealth({
      connectionUri: 'http://localhost:3567',
      apiDomain: 'http://localhost:3001',
      websiteDomain: 'http://localhost:4273',
      fetchImpl,
    })).resolves.toEqual({
      configured: true,
      reachable: true,
      ready: true,
      apiVersion: '5.0',
      error: null,
    })
  })

  it('reports invalid payloads as not ready', async () => {
    const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(
      new Response(JSON.stringify({ ok: true }), {
        status: 200,
        headers: {
          'content-type': 'application/json',
        },
      }),
    )

    await expect(probeSuperTokensCoreHealth({
      connectionUri: 'http://localhost:3567',
      apiDomain: 'http://localhost:3001',
      websiteDomain: 'http://localhost:4273',
      fetchImpl,
    })).resolves.toEqual({
      configured: true,
      reachable: false,
      ready: false,
      apiVersion: null,
      error: 'invalid_payload',
    })
  })

  it('reports request failures without throwing', async () => {
    const fetchImpl = vi.fn<typeof fetch>().mockRejectedValue(new Error('connect ECONNREFUSED'))

    await expect(probeSuperTokensCoreHealth({
      connectionUri: 'http://localhost:3567',
      apiDomain: 'http://localhost:3001',
      websiteDomain: 'http://localhost:4273',
      fetchImpl,
    })).resolves.toEqual({
      configured: true,
      reachable: false,
      ready: false,
      apiVersion: null,
      error: 'unreachable',
    })
  })
})
