import { render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { QueryProvider } from '../query-provider';

vi.mock('next-intl', () => ({
  useTranslations: () => (key: string) => key,
}));

vi.mock('@/lib/query-client', async () => {
  const { QueryClient } = await import('@tanstack/react-query');
  return { getQueryClient: () => new QueryClient() };
});

function Boom() {
  throw new Error('query-fail');
}

describe('QueryProvider', () => {
  let spy: ReturnType<typeof vi.spyOn>;

  beforeEach(() => {
    spy = vi.spyOn(console, 'error').mockImplementation(() => {});
  });

  afterEach(() => {
    spy.mockRestore();
  });

  it('renders children under provider', () => {
    render(
      <QueryProvider>
        <div>ok</div>
      </QueryProvider>,
    );
    expect(screen.getByText('ok')).toBeInTheDocument();
  });

  it('catches thrown errors and renders fallback with retry button', () => {
    render(
      <QueryProvider>
        <Boom />
      </QueryProvider>,
    );
    // error.description & common.retry keys surface via mocked translator
    expect(screen.getByRole('alert')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'common.retry' })).toBeInTheDocument();
  });

  it('surfaces the underlying error message in fallback', () => {
    render(
      <QueryProvider>
        <Boom />
      </QueryProvider>,
    );
    expect(screen.getByText('query-fail')).toBeInTheDocument();
  });
});
