/**
 * Tests for Linker ContentList
 */
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { BrowserRouter } from 'react-router';
import ContentList from '../ContentList';
import { linkerApi } from '../../../api/linker.api';
import { fetchContent } from '../../../services/api';

vi.mock('../../../api/linker.api');
vi.mock('../../../services/api');
vi.mock('../../../store/sectorStore', () => ({
  useSectorStore: () => ({ activeSector: { id: 1, name: 'Test Sector' } }),
}));
vi.mock('../../../store/pageSizeStore', () => ({
  usePageSizeStore: () => ({ pageSize: 10 }),
}));
vi.mock('../../../components/ui/toast/ToastContainer', () => ({
  useToast: () => ({
    success: vi.fn(),
    error: vi.fn(),
  }),
}));

describe('LinkerContentList', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders content list title', () => {
    (fetchContent as any).mockResolvedValue({ results: [], count: 0 });
    
    render(
      <BrowserRouter>
        <ContentList />
      </BrowserRouter>
    );
    
    expect(screen.getByText('Link Content')).toBeInTheDocument();
  });

  it('displays content items', async () => {
    (fetchContent as any).mockResolvedValue({
      results: [
        { id: 1, title: 'Test Content', source: 'igny8', internal_links: [], linker_version: 0 },
      ],
      count: 1,
    });
    
    render(
      <BrowserRouter>
        <ContentList />
      </BrowserRouter>
    );
    
    await waitFor(() => {
      expect(screen.getByText('Test Content')).toBeInTheDocument();
    });
  });

  it('calls linker API when Add Links button is clicked', async () => {
    (fetchContent as any).mockResolvedValue({
      results: [
        { id: 1, title: 'Test Content', source: 'igny8', internal_links: [], linker_version: 0 },
      ],
      count: 1,
    });
    
    (linkerApi.process as any).mockResolvedValue({
      content_id: 1,
      links_added: 2,
      links: [{ id: 1 }, { id: 2 }],
      linker_version: 1,
    });
    
    render(
      <BrowserRouter>
        <ContentList />
      </BrowserRouter>
    );
    
    await waitFor(() => {
      const addLinksButton = screen.getByText('Add Links');
      fireEvent.click(addLinksButton);
    });
    
    await waitFor(() => {
      expect(linkerApi.process).toHaveBeenCalledWith(1);
    });
  });

  it('shows loading state', () => {
    (fetchContent as any).mockImplementation(() => new Promise(() => {}));
    
    render(
      <BrowserRouter>
        <ContentList />
      </BrowserRouter>
    );
    
    expect(screen.getByText('Loading content...')).toBeInTheDocument();
  });
});

