/**
 * Tests pour PlaylistVersionHistory
 * T0509: Create Playlist Version History
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { PlaylistVersionHistory } from './PlaylistVersionHistory';

// Mock apiClient
vi.mock('@/services/api/client', () => ({
  apiClient: {
    get: vi.fn(),
    post: vi.fn(),
  },
}));

// Mock useToast
vi.mock('@/hooks/useToast', () => ({
  useToast: vi.fn(() => ({
    toast: vi.fn(),
  })),
}));

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
    },
  },
});

const wrapper = ({ children }: { children: React.ReactNode }) => (
  <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);

describe('PlaylistVersionHistory', () => {
  const mockVersions = {
    versions: [
      {
        id: 1,
        playlist_id: 1,
        user_id: 1,
        version: 1,
        action: 'created',
        title: 'Playlist Original',
        description: 'Description originale',
        is_public: true,
        created_at: '2024-01-01T00:00:00Z',
        user: { id: 1, username: 'user1' },
      },
      {
        id: 2,
        playlist_id: 1,
        user_id: 1,
        version: 2,
        action: 'updated',
        title: 'Playlist Modifiée',
        description: 'Description modifiée',
        is_public: true,
        created_at: '2024-01-02T00:00:00Z',
        user: { id: 1, username: 'user1' },
      },
    ],
    total: 2,
    limit: 20,
    offset: 0,
  };

  beforeEach(() => {
    vi.clearAllMocks();
    queryClient.clear();
  });

  it('should render history button', () => {
    render(<PlaylistVersionHistory playlistId={1} />, { wrapper });

    const button = screen.getByLabelText("Voir l'historique des versions");
    expect(button).toBeInTheDocument();
  });

  it('should open dialog when button is clicked', async () => {
    const user = userEvent.setup();
    const { apiClient } = await import('@/services/api/client');
    vi.mocked(apiClient.get).mockResolvedValueOnce({
      data: mockVersions,
    } as any);

    render(<PlaylistVersionHistory playlistId={1} />, { wrapper });

    const button = screen.getByLabelText("Voir l'historique des versions");
    await user.click(button);

    await waitFor(() => {
      expect(screen.getByText('Historique des versions')).toBeInTheDocument();
    });
  });

  it('should display versions when loaded', async () => {
    const user = userEvent.setup();
    const { apiClient } = await import('@/services/api/client');
    vi.mocked(apiClient.get).mockResolvedValueOnce({
      data: mockVersions,
    } as any);

    render(<PlaylistVersionHistory playlistId={1} />, { wrapper });

    const button = screen.getByLabelText("Voir l'historique des versions");
    await user.click(button);

    await waitFor(() => {
      expect(screen.getByText('Version 1')).toBeInTheDocument();
      expect(screen.getByText('Version 2')).toBeInTheDocument();
    });
  });

  it('should show restore button when canRestore is true', async () => {
    const user = userEvent.setup();
    const { apiClient } = await import('@/services/api/client');
    vi.mocked(apiClient.get).mockResolvedValueOnce({
      data: mockVersions,
    } as any);

    render(<PlaylistVersionHistory playlistId={1} canRestore={true} />, {
      wrapper,
    });

    const button = screen.getByLabelText("Voir l'historique des versions");
    await user.click(button);

    await waitFor(() => {
      const restoreButtons = screen.getAllByLabelText(/Restaurer la version/);
      expect(restoreButtons.length).toBeGreaterThan(0);
    });
  });

  it('should not show restore button when canRestore is false', async () => {
    const user = userEvent.setup();
    const { apiClient } = await import('@/services/api/client');
    vi.mocked(apiClient.get).mockResolvedValueOnce({
      data: mockVersions,
    } as any);

    render(<PlaylistVersionHistory playlistId={1} canRestore={false} />, {
      wrapper,
    });

    const button = screen.getByLabelText("Voir l'historique des versions");
    await user.click(button);

    await waitFor(() => {
      expect(screen.getByText('Version 1')).toBeInTheDocument();
    });

    const restoreButtons = screen.queryAllByLabelText(/Restaurer la version/);
    expect(restoreButtons.length).toBe(0);
  });
});
