import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from '@cameleer/design-system';
import { CheckpointDetailDrawer } from './index';

// Mock the logs hook so the test doesn't try to fetch
vi.mock('../../../../api/queries/logs', () => ({
  useInfiniteApplicationLogs: () => ({ items: [], isLoading: false, hasNextPage: false, fetchNextPage: vi.fn(), isFetchingNextPage: false, refresh: vi.fn() }),
}));

const baseDep: any = {
  id: 'aaa11111-2222-3333-4444-555555555555',
  appId: 'a', appVersionId: 'v6id', environmentId: 'e',
  status: 'STOPPED', targetState: 'STOPPED', deploymentStrategy: 'BLUE_GREEN',
  replicaStates: [{ index: 0, containerId: 'c', containerName: 'n', status: 'STOPPED' }],
  deployStage: null, containerId: null, containerName: null, errorMessage: null,
  deployedAt: '2026-04-23T10:35:00Z', stoppedAt: '2026-04-23T10:52:00Z',
  createdAt: '2026-04-23T10:35:00Z', createdBy: 'alice',
  deployedConfigSnapshot: { jarVersionId: 'v6id', agentConfig: null, containerConfig: {}, sensitiveKeys: null },
};

const v: any = {
  id: 'v6id', appId: 'a', version: 6,
  jarPath: '/j', jarChecksum: 'c', jarFilename: 'my-app-1.2.3.jar',
  jarSizeBytes: 1, detectedRuntimeType: null, detectedMainClass: null,
  uploadedAt: '2026-04-23T10:00:00Z',
};

function renderDrawer(propOverrides: Partial<Parameters<typeof CheckpointDetailDrawer>[0]> = {}) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <QueryClientProvider client={qc}>
      <ThemeProvider>
        <CheckpointDetailDrawer
          open
          onClose={() => {}}
          deployment={baseDep}
          version={v}
          appSlug="my-app"
          envSlug="prod"
          onRestore={() => {}}
          {...propOverrides}
        />
      </ThemeProvider>
    </QueryClientProvider>
  );
}

describe('CheckpointDetailDrawer', () => {
  it('renders header with version + jar + status', () => {
    renderDrawer();
    expect(screen.getByText('v6')).toBeInTheDocument();
    expect(screen.getByText('my-app-1.2.3.jar')).toBeInTheDocument();
    expect(screen.getByText('STOPPED')).toBeInTheDocument();
  });

  it('renders meta line with createdBy', () => {
    renderDrawer();
    expect(screen.getByText(/alice/)).toBeInTheDocument();
  });

  it('Config tab is selected by default', () => {
    renderDrawer();
    // Tabs from DS may render as buttons or tabs role — be lenient on the query
    const configTab = screen.getByText(/^config$/i);
    expect(configTab).toBeInTheDocument();
  });

  it('disables Restore when JAR is pruned', () => {
    renderDrawer({ version: undefined });
    expect(screen.getByRole('button', { name: /restore/i })).toBeDisabled();
  });
});
