// src/providers/ApiProvider.test.tsx
import React, { useContext } from 'react';
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { ApiProvider } from './ApiProvider';
import { ApiContext } from '../contexts/ApiContext';
import * as apiClient from '../services/apiClient';

// Mock the apiClient module.
// Since ApiProvider and ApiContext import * as apiClient, mocking it ensures
// we control the reference identity and can verify it's being passed correctly.
vi.mock('../services/apiClient', () => ({
  fetchFlyers: vi.fn(),
  fetchMasterItems: vi.fn(),
  // Add other mocked methods as needed for the shape to be valid-ish
}));

describe('ApiProvider & ApiContext', () => {
  const TestConsumer = () => {
    const contextValue = useContext(ApiContext);
    // We check if the context value is strictly equal to the imported module
    return (
      <div>
        <span data-testid="value-check">
          {contextValue === apiClient ? 'Matches apiClient' : 'Does not match'}
        </span>
      </div>
    );
  };

  it('renders children correctly', () => {
    render(
      <ApiProvider>
        <div data-testid="child">Child Content</div>
      </ApiProvider>
    );
    expect(screen.getByTestId('child')).toBeInTheDocument();
    expect(screen.getByText('Child Content')).toBeInTheDocument();
  });

  it('provides the apiClient module via context', () => {
    render(
      <ApiProvider>
        <TestConsumer />
      </ApiProvider>
    );
    expect(screen.getByTestId('value-check')).toHaveTextContent('Matches apiClient');
  });

  it('ApiContext has apiClient as the default value (when no provider is present)', () => {
    // This verifies the logic in ApiContext.tsx: createContext(apiClient)
    render(<TestConsumer />);
    expect(screen.getByTestId('value-check')).toHaveTextContent('Matches apiClient');
  });
});