/**
 * ADMFE-R15-01 — Render-contract guard: AuditLogs Show
 *
 * Renders with controller-shaped props (audit_log snake_case key, action field
 * only — event column is dropped per CLAUDE.md gotcha #3).  Before the fix the
 * component destructured `auditLog` (camelCase) while the controller sends
 * `audit_log`, so auditLog.id crashed immediately.
 */
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';

import type { AdminAuditLogShowProps } from '@/types/admin';

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

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/audit-logs/7',
      props: {
        auth: { user: { name: 'Admin', email: 'admin@test.com' } },
        features: {
          billing: false,
          socialAuth: false,
          emailVerification: true,
          apiTokens: true,
          userSettings: true,
          notifications: false,
        },
      },
    })),
    Link: ({
      children,
      href,
      ...rest
    }: {
      children: React.ReactNode;
      href: string;
      className?: string;
    }) => (
      <a href={href} {...rest}>
        {children}
      </a>
    ),
  };
});

import AdminAuditLogShow from './Show';

const defaultProps: AdminAuditLogShowProps = {
  audit_log: {
    id: 7,
    action: 'admin.login',
    user_id: 1,
    user_name: 'Alice',
    user_email: 'alice@test.com',
    ip: '1.2.3.4',
    user_agent: 'Mozilla',
    metadata: null,
    created_at: '2026-01-01T00:00:00.000Z',
  },
  impersonation_session: null,
};

describe('AdminAuditLogShow — ADMFE-R15-01 render-contract guard', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders without crashing when given controller-shaped props (audit_log key)', () => {
    // Before fix: TypeError: Cannot read properties of undefined (reading 'id')
    // because the component destructured `auditLog` while controller sends `audit_log`.
    expect(() => render(<AdminAuditLogShow {...defaultProps} />)).not.toThrow();
  });

  it('renders the audit log ID in the page title', () => {
    render(<AdminAuditLogShow {...defaultProps} />);
    // Page title and breadcrumb both reference the ID
    expect(screen.getByText('#7')).toBeInTheDocument();
  });

  it('renders the human-friendly action label', () => {
    render(<AdminAuditLogShow {...defaultProps} />);
    // getAuditLabel('admin.login') should resolve to a human label
    // The badge must be present (even if the exact label text varies)
    // We verify the action value is at least in the DOM via the badge title attribute
    const badge = document.querySelector('[title]');
    expect(badge).not.toBeNull();
  });

  it('renders user link when user info is present', () => {
    render(<AdminAuditLogShow {...defaultProps} />);
    expect(screen.getByText(/Alice/)).toBeInTheDocument();
  });

  it('renders System fallback when user_name is null', () => {
    render(
      <AdminAuditLogShow
        {...defaultProps}
        audit_log={{ ...defaultProps.audit_log, user_name: null, user_email: null }}
      />,
    );
    // "System" appears in both sidebar nav and in the user field — use getAllByText
    const systemElements = screen.getAllByText('System');
    expect(systemElements.length).toBeGreaterThanOrEqual(1);
  });

  it('does not render impersonation card when action is not impersonation_started', () => {
    render(<AdminAuditLogShow {...defaultProps} />);
    expect(screen.queryByText('Impersonation Session')).not.toBeInTheDocument();
  });

  it('renders impersonation session card when action is impersonation_started', () => {
    render(
      <AdminAuditLogShow
        {...defaultProps}
        audit_log={{ ...defaultProps.audit_log, action: 'admin.impersonation_started' }}
        impersonation_session={{
          stopped_at: '2026-01-01T01:00:00.000Z',
          duration_seconds: 3600,
          stopped_log_id: 99,
        }}
      />,
    );
    expect(screen.getByText('Impersonation Session')).toBeInTheDocument();
    expect(screen.getByText(/1h/)).toBeInTheDocument();
  });
});
