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

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

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

  it('accepts Apify tokens stored in provider-specific apiToken shape', () => {
    expect(adapter.validateCredentials({ apiToken: 'apify_api_test' })).toBe(true)
  })

  it('accepts Apify tokens stored in generic api-key shape', () => {
    expect(adapter.validateCredentials({ apiKey: 'apify_api_test' })).toBe(true)
  })

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

  it('verifies credentials against the Apify current-user endpoint', async () => {
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      json: vi.fn().mockResolvedValue({
        data: {
          username: 'elevasis',
          plan: {
            id: 'TEAM',
            description: 'Team plan'
          }
        }
      })
    })
    globalThis.fetch = fetchMock as unknown as typeof fetch

    await expect(adapter.verify({ apiKey: ' apify_api_test ' })).resolves.toEqual({
      ok: true,
      provider: 'apify',
      username: 'elevasis',
      plan: 'TEAM'
    })

    expect(fetchMock).toHaveBeenCalledWith('https://api.apify.com/v2/users/me', {
      method: 'GET',
      headers: {
        Authorization: 'Bearer apify_api_test',
        'Content-Type': 'application/json'
      }
    })
  })
})
