import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { RequireRole } from './RequireRole';
import * as useAuthModule from '../hooks/useAuth';

function mockAuth(user: { roles: string[] } | null) {
  vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
    user: user as never,
    loading: false,
    login: vi.fn(),
    logout: vi.fn(),
    setUser: vi.fn(),
  });
}

describe('<RequireRole>', () => {
  it('renders children when the user has the required role', () => {
    mockAuth({ roles: ['Admin'] });
    render(
      <RequireRole role="Admin">
        <div>Admin-only content</div>
      </RequireRole>,
    );
    expect(screen.getByText('Admin-only content')).toBeInTheDocument();
  });

  it('renders a 403 when the user is missing the required role', () => {
    mockAuth({ roles: ['User'] });
    render(
      <RequireRole role="Admin">
        <div>Admin-only content</div>
      </RequireRole>,
    );
    expect(screen.queryByText('Admin-only content')).not.toBeInTheDocument();
    expect(screen.getByText('403')).toBeInTheDocument();
  });

  it('renders a 403 when the user is null (unauthenticated edge)', () => {
    mockAuth(null);
    render(
      <RequireRole role="Admin">
        <div>Admin-only content</div>
      </RequireRole>,
    );
    expect(screen.getByText('403')).toBeInTheDocument();
  });
});
