import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { DeploymentProvider, useDeployment } from './DeploymentProvider'

vi.mock('../api', () => ({ getDeployment: vi.fn() }))
import { getDeployment } from '../api'

function Probe() {
  const { name, defaultProjectId, projects, loading } = useDeployment()
  return (
    <div>
      <span data-testid="loading">{String(loading)}</span>
      <span data-testid="name">{name}</span>
      <span data-testid="default">{defaultProjectId || ''}</span>
      <span data-testid="count">{projects.length}</span>
    </div>
  )
}

describe('DeploymentProvider', () => {
  beforeEach(() => vi.clearAllMocks())

  it('provides fetched deployment config', async () => {
    getDeployment.mockResolvedValue({
      name: 'Wiggleverse',
      tagline: 'a directory',
      default_project_id: 'ohm',
      projects: [{ id: 'ohm', name: 'OHM', type: 'document', visibility: 'public' }],
    })
    render(<DeploymentProvider><Probe /></DeploymentProvider>)
    await waitFor(() => expect(screen.getByTestId('loading').textContent).toBe('false'))
    expect(screen.getByTestId('name').textContent).toBe('Wiggleverse')
    expect(screen.getByTestId('default').textContent).toBe('ohm')
    expect(screen.getByTestId('count').textContent).toBe('1')
  })

  it('falls back gracefully when the fetch fails (empty, not wedged)', async () => {
    getDeployment.mockRejectedValue(new Error('boom'))
    render(<DeploymentProvider><Probe /></DeploymentProvider>)
    await waitFor(() => expect(screen.getByTestId('loading').textContent).toBe('false'))
    expect(screen.getByTestId('name').textContent).toBe('')
    expect(screen.getByTestId('count').textContent).toBe('0')
  })
})