import { render, waitFor } from '@testing-library/react';
import { ThemeProvider } from '../../theme';
import type { Me } from '@/services/auth/types';

const mockReplace = jest.fn();

jest.mock('next/navigation', () => ({
  ...jest.requireActual('next/navigation'),
  useRouter: () => ({ replace: mockReplace }),
}));
jest.mock('next-intl', () => ({ useLocale: () => 'fa', useTranslations: () => (key: string) => key }));

let meResult: { data?: Partial<Me>; isError: boolean };
jest.mock('@/services/auth', () => ({ useMe: () => meResult }));

import RoleRouter from './RoleRouter';

function renderRouter(intendedRole?: 'customer' | 'nurse') {
  render(
    <ThemeProvider>
      <RoleRouter intendedRole={intendedRole} />
    </ThemeProvider>,
  );
}

describe('<RoleRouter/>', () => {
  beforeEach(() => mockReplace.mockReset());

  it('does not navigate while /me is loading', () => {
    meResult = { data: undefined, isError: false };
    renderRouter();
    expect(mockReplace).not.toHaveBeenCalled();
  });

  it('routes a customer to the family app', async () => {
    meResult = { data: { roles: ['customer'] }, isError: false };
    renderRouter();
    await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/fa/'));
  });

  it('routes a nurse to the nurse app', async () => {
    meResult = { data: { roles: ['nurse'] }, isError: false };
    renderRouter();
    await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/fa/nurse'));
  });

  it('routes a role-less user to select-role, carrying nurse intent', async () => {
    meResult = { data: { roles: [] }, isError: false };
    renderRouter('nurse');
    await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/fa/select-role?role=nurse'));
  });

  it('falls back to login when /me errors', async () => {
    meResult = { data: undefined, isError: true };
    renderRouter();
    await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/fa/login'));
  });
});
