import { afterEach, describe, expect, it, vi } from 'vitest'
import { ApolloAdapter } from './apollo-adapter'

describe('ApolloAdapter', () => {
  const adapter = new ApolloAdapter()
  const originalFetch = globalThis.fetch

  afterEach(() => {
    vi.restoreAllMocks()
    globalThis.fetch = originalFetch
  })

  it('accepts Apollo API keys stored in generic apiKey shape', () => {
    expect(adapter.validateCredentials({ apiKey: 'apollo-key' })).toBe(true)
  })

  it('accepts Apollo API keys stored in legacy Apollo alias shapes', () => {
    expect(adapter.validateCredentials({ apolloApiKey: 'apollo-key' })).toBe(true)
    expect(adapter.validateCredentials({ APOLLO_API_KEY: 'apollo-key' })).toBe(true)
    expect(adapter.validateCredentials({ key: 'apollo-key' })).toBe(true)
  })

  it('rejects blank tokens', () => {
    expect(adapter.validateCredentials({ apiKey: '   ' })).toBe(false)
  })

  it('verifies credentials against the Apollo auth health endpoint', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true
    })
    globalThis.fetch = fetchMock as unknown as typeof fetch

    await expect(adapter.verify({ apiKey: ' apollo-key ' })).resolves.toEqual({
      ok: true,
      provider: 'apollo',
      authenticated: true
    })

    expect(fetchMock).toHaveBeenCalledWith('https://api.apollo.io/v1/auth/health', {
      method: 'GET',
      headers: {
        accept: 'application/json',
        'x-api-key': 'apollo-key',
        authorization: 'Bearer apollo-key'
      }
    })
  })
})
