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

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,
    router: {
      post: vi.fn(),
      get: vi.fn(),
      on: vi.fn(() => vi.fn()),
    },
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    Link: ({ children, href }: { children: React.ReactNode; href: string }) => (
      <a href={href}>{children}</a>
    ),
    usePage: vi.fn(() => ({
      url: '/admin/analysis-runs/5',
      props: {
        auth: { user: { id: 1, name: 'Admin', email: 'admin@test.com', is_admin: true }, impersonating: false },
        features: { billing: false, socialAuth: false, emailVerification: false, apiTokens: false, userSettings: false, notifications: false, onboarding: false, apiDocs: false, twoFactor: false, webhooks: false, admin: true },
        flash: {}, errors: {}, notifications_unread_count: 0, sites: [], limits: null, active_jobs: [], ai_max_batch_size: 10, ai_defaults: {}, polling_interval_ms: 5000, admin_failed_job_count: 0,
      },
    })),
  };
});

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

import AnalysisRunsShow from './Show';

const makeRun = (overrides = {}) => ({
  id: 5,
  site_id: 50,
  site_name: 'Analysis Site',
  site_domain: 'analysis.com',
  status: 'failed',
  before_start: null,
  before_end: null,
  after_start: null,
  after_end: null,
  summary: null,
  error: 'GSC fetch failed',
  is_scheduled: false,
  started_at: null,
  completed_at: null,
  duration_seconds: null,
  findings_count: 0,
  recommendations_count: 0,
  ai_jobs_count: 0,
  created_at: '2026-06-01T00:00:00Z',
  ...overrides,
});

describe('AnalysisRuns/Show', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('shows Retry button when run status is failed', () => {
    render(<AnalysisRunsShow run={makeRun()} />);
    expect(screen.getByRole('button', { name: /retry analysis run #5/i })).toBeInTheDocument();
  });

  it('does not show Retry button when status is completed', () => {
    render(<AnalysisRunsShow run={makeRun({ status: 'completed' })} />);
    expect(screen.queryByRole('button', { name: /retry analysis run/i })).not.toBeInTheDocument();
  });

  it('does not fire router.post immediately on Retry click — opens dialog first', async () => {
    const user = userEvent.setup();
    render(<AnalysisRunsShow run={makeRun()} />);
    await user.click(screen.getByRole('button', { name: /retry analysis run #5/i }));
    expect(router.post).not.toHaveBeenCalled();
    expect(screen.getByRole('alertdialog')).toBeInTheDocument();
  });

  it('fires router.post with analysis-runs retry route when confirmed', async () => {
    const user = userEvent.setup();
    render(<AnalysisRunsShow run={makeRun()} />);
    await user.click(screen.getByRole('button', { name: /retry analysis run #5/i }));
    await user.click(screen.getByRole('button', { name: /retry run/i }));
    expect(router.post).toHaveBeenCalledTimes(1);
    expect(router.post).toHaveBeenCalledWith(
      expect.stringContaining('analysis-runs'),
      expect.anything(),
      expect.anything(),
    );
  });
});
