import { renderHook, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AuthProvider, useAuth } from './AuthContext';
import { ReactNode } from 'react';
import { BrowserRouter } from 'react-router-dom';
import { ToastProvider } from './ToastContext';

// Mock des dépendances
vi.mock('@/services/authService', () => ({
  authService: {
    getCurrentUser: vi.fn().mockResolvedValue({ id: '1', username: 'test' }),
    login: vi.fn(),
    register: vi.fn(),
    logout: vi.fn(),
  },
}));

vi.mock('@/services/tokenStorage', () => ({
  getAccessToken: vi.fn(() => 'mock-token'),
  clearTokens: vi.fn(),
}));

const wrapper = ({ children }: { children: ReactNode }) => (
  <BrowserRouter>
    <AuthProvider>{children}</AuthProvider>
  </BrowserRouter>
);

describe('AuthContext', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockGetCurrentUser.mockResolvedValue({ id: '1', username: 'test' });
    localStorage.clear();
  });

  it('should provide auth context', () => {
    const { result } = renderHook(() => useAuth(), { wrapper });
    
    expect(result.current).toBeDefined();
    expect(result.current).toHaveProperty('user');
    expect(result.current).toHaveProperty('isAuthenticated');
    expect(result.current).toHaveProperty('isLoading');
  });

  it('should have initial loading state', () => {
    const { result } = renderHook(() => useAuth(), { wrapper });
    
    // Le contexte devrait être en cours de chargement initialement
    expect(result.current).toBeDefined();
  });

  it('should provide login function', () => {
    const { result } = renderHook(() => useAuth(), { wrapper });
    
    expect(result.current).toHaveProperty('login');
    expect(typeof result.current.login).toBe('function');
  });

  it('should provide logout function', () => {
    const { result } = renderHook(() => useAuth(), { wrapper });
    
    expect(result.current).toHaveProperty('logout');
    expect(typeof result.current.logout).toBe('function');
  });

  it('should provide register function', () => {
    const { result } = renderHook(() => useAuth(), { wrapper });
    
    expect(result.current).toHaveProperty('register');
    expect(typeof result.current.register).toBe('function');
  });
});

