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

import { usePage } from '@inertiajs/react';

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    usePage: vi.fn(() => ({
      url: '/admin/cache',
      props: {
        auth: { user: { name: 'Admin', email: 'admin@test.com', admin_role: 'operator' } },
        features: {
          billing: false,
          socialAuth: false,
          emailVerification: true,
          apiTokens: true,
          userSettings: true,
          notifications: false,
          onboarding: false,
          apiDocs: false,
          twoFactor: false,
          webhooks: false,
          admin: true,
        },
      },
    })),
    Link: ({
      children,
      href,
      ...rest
    }: {
      children: React.ReactNode;
      href: string;
      className?: string;
    }) => (
      <a href={href} {...rest}>
        {children}
      </a>
    ),
    router: {
      post: vi.fn(),
      on: vi.fn(() => vi.fn()),
    },
  };
});

vi.mock('@/Components/theme/use-theme', () => ({
  useTheme: vi.fn(() => ({ theme: 'system', setTheme: vi.fn(), resolvedTheme: 'light' })),
}));

import CacheIndex from './Index';

const makeGroups = () => [
  { name: 'admin', prefix: 'admin.', description: 'Admin panel stats, charts, and counters' },
  { name: 'limits', prefix: 'limit.', description: 'User and site usage limit caches' },
  { name: 'gsc', prefix: 'gsc.', description: 'Google Search Console data caches' },
  { name: 'user', prefix: 'user.', description: 'User session and preference caches' },
];

const makeAdminKeys = () => [
  { key: 'admin.metrics', cached: true },
  { key: 'admin.users', cached: false },
];

describe('CacheIndex', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders page heading', () => {
    render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
    expect(screen.getAllByText('Cache Management').length).toBeGreaterThanOrEqual(1);
  });

  it('renders cache groups', () => {
    render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
    expect(screen.getByText('admin')).toBeInTheDocument();
    expect(screen.getByText('limits')).toBeInTheDocument();
    expect(screen.getByText('gsc')).toBeInTheDocument();
  });

  it('shows flush buttons for operator role', () => {
    render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
    const flushButtons = screen.getAllByRole('button', { name: /Flush/i });
    expect(flushButtons.length).toBeGreaterThan(0);
  });

  it('shows cached/empty badge for admin keys', () => {
    render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
    expect(screen.getByText('Cached')).toBeInTheDocument();
    expect(screen.getByText('Empty')).toBeInTheDocument();
  });

  it('does not show Flush All button for operator (super_admin only)', () => {
    render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
    expect(screen.queryByText('Flush All Admin Caches')).not.toBeInTheDocument();
  });

  it('shows Flush All button for super_admin', () => {
    vi.mocked(usePage).mockReturnValueOnce({
      url: '/admin/cache',
      props: {
        auth: { user: { name: 'SuperAdmin', email: 'super@test.com', admin_role: 'super_admin' } },
        features: {},
      },
    } as unknown as ReturnType<typeof usePage>);

    render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
    expect(screen.getByText('Flush All Admin Caches')).toBeInTheDocument();
  });

  describe('viewer role', () => {
    beforeEach(() => {
      vi.mocked(usePage).mockReturnValue({
        url: '/admin/cache',
        props: {
          auth: { user: { name: 'Viewer', email: 'viewer@test.com', admin_role: 'viewer' } },
          features: {},
        },
      } as unknown as ReturnType<typeof usePage>);
    });

    it('does not show Flush buttons for viewer role', () => {
      render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
      expect(screen.queryAllByRole('button', { name: /Flush/i })).toHaveLength(0);
    });

    it('does not show Flush All Admin Caches button for viewer role', () => {
      render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
      expect(screen.queryByText('Flush All Admin Caches')).not.toBeInTheDocument();
    });

    it('still renders cache group names for viewer role', () => {
      render(<CacheIndex groups={makeGroups()} admin_keys={makeAdminKeys()} />);
      expect(screen.getByText('admin')).toBeInTheDocument();
      expect(screen.getByText('gsc')).toBeInTheDocument();
    });
  });
});
