import { render, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from '../../../theme';

jest.mock('next-intl', () => ({
  useTranslations: () => (key: string) => key,
  useLocale: () => 'en',
}));
jest.mock('notistack', () => ({ useSnackbar: () => ({ enqueueSnackbar: jest.fn() }) }));

// This is a behavioural test of the two-stage-disclosure gate; it uses the in-memory bookings mock as
// its data fixture (seeded booking 5001 + care instructions). Pin the seam to the mock so the test is
// independent of the production `USE_BOOKINGS_MOCK` flag (flipped to real in refinement-phase-4).
jest.mock('@/services/bookings/apis', () => ({
  bookingsApi: jest.requireActual('@/services/bookings/apis/mockApi').bookingsMockApi,
}));

import BookingDetailView from './BookingDetailView';
import { bookingsApi } from '@/services/bookings/apis';

function renderView(viewerRole: 'customer' | 'nurse') {
  const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <QueryClientProvider client={queryClient}>
      <ThemeProvider>
        <BookingDetailView bookingId={5001} viewerRole={viewerRole} />
      </ThemeProvider>
    </QueryClientProvider>,
  );
}

describe('<BookingDetailView/> — two-stage disclosure gate', () => {
  afterEach(() => jest.restoreAllMocks());

  it('customer: never fetches care instructions and shows the "visible to your nurse only" affordance', async () => {
    const careSpy = jest.spyOn(bookingsApi, 'getCareInstructions');
    renderView('customer');

    // Wait for the booking to load and the locked affordance to render.
    await waitFor(() => expect(screen.getByText('care_locked_title')).toBeInTheDocument());

    // The hard gate: the client must not even request the clinical record for the customer.
    expect(careSpy).not.toHaveBeenCalled();
    expect(screen.queryByText('care_title')).not.toBeInTheDocument();
  });

  it('assigned nurse: fetches and renders the gated care instructions on a confirmed booking', async () => {
    const careSpy = jest.spyOn(bookingsApi, 'getCareInstructions');
    renderView('nurse');

    await waitFor(() => expect(careSpy).toHaveBeenCalledWith(5001, 'nurse'));
    // The nurse never sees the customer's locked placeholder.
    expect(screen.queryByText('care_locked_title')).not.toBeInTheDocument();
    await waitFor(() => expect(screen.getByText('care_title')).toBeInTheDocument());
  });
});
