// src/components/AdminRoute.test.tsx
import React from 'react';
import { screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { Routes, Route } from 'react-router-dom';
import { AdminRoute } from './AdminRoute';
import type { Profile } from '../types';
import { createMockProfile } from '../tests/utils/mockFactories';
import { renderWithProviders } from '../tests/utils/renderWithProviders';

// Unmock the component to test the real implementation
vi.unmock('./AdminRoute');

const AdminContent = () => <div>Admin Page Content</div>;
const HomePage = () => <div>Home Page</div>;

const renderWithRouter = (profile: Profile | null, initialPath: string) => {
  renderWithProviders(
    <Routes>
      <Route path="/" element={<HomePage />} />
      <Route path="/admin" element={<AdminRoute profile={profile} />}>
        <Route index element={<AdminContent />} />
      </Route>
    </Routes>,
    { initialEntries: [initialPath] },
  );
};

describe('AdminRoute', () => {
  it('should render the admin content when user has admin role', () => {
    const adminProfile: Profile = createMockProfile({ role: 'admin' });
    renderWithRouter(adminProfile, '/admin');

    expect(screen.getByText('Admin Page Content')).toBeInTheDocument();
    expect(screen.queryByText('Home Page')).not.toBeInTheDocument();
  });

  it('should redirect to home page when user does not have admin role', () => {
    const userProfile: Profile = createMockProfile({ role: 'user' });
    renderWithRouter(userProfile, '/admin');

    // The user is redirected, so we should see the home page content
    expect(screen.getByText('Home Page')).toBeInTheDocument();
    expect(screen.queryByText('Admin Page Content')).not.toBeInTheDocument();
  });

  it('should redirect to home page when profile is null', () => {
    renderWithRouter(null, '/admin');

    // The user is redirected, so we should see the home page content
    expect(screen.getByText('Home Page')).toBeInTheDocument();
    expect(screen.queryByText('Admin Page Content')).not.toBeInTheDocument();
  });
});
