import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import Account from './Account';
import { AuthProvider } from '../auth/AuthContext';
import { apiFetch } from '../lib/api';
import { clearToken, getToken, setToken } from '../lib/auth-storage';

// Mock the network layer so no real requests are made.
vi.mock('../lib/api', () => ({
  apiFetch: vi.fn(),
}));

const mockedApiFetch = vi.mocked(apiFetch);

function renderAccount() {
  const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <QueryClientProvider client={queryClient}>
      <AuthProvider>
        <Account />
      </AuthProvider>
    </QueryClientProvider>
  );
}

describe('Account', () => {
  beforeEach(() => {
    mockedApiFetch.mockReset();
    mockedApiFetch.mockResolvedValue({
      user: { id: 'u1', email: 'worker@solelog.local', name: 'Test Werker' },
    });
  });

  afterEach(() => {
    clearToken();
    vi.clearAllMocks();
  });

  it('shows the signed-in user name and email', async () => {
    renderAccount();
    expect(await screen.findByText('Test Werker')).toBeInTheDocument();
    expect(screen.getByText('worker@solelog.local')).toBeInTheDocument();
  });

  it('logs out: clicking Uitloggen clears the token', async () => {
    setToken('tok');
    const user = userEvent.setup();
    renderAccount();
    await user.click(screen.getByRole('button', { name: 'Uitloggen' }));
    expect(getToken()).toBeNull();
  });
});
