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

import { AgentWorkspaceShell } from '../../src/components/agent-workspace/agent-workspace-shell';

const { mockUseMutation, mockUseQuery } = vi.hoisted(() => ({
  mockUseMutation: vi.fn(() => vi.fn()),
  mockUseQuery: vi.fn(),
}));

vi.mock('convex/react', () => ({
  useMutation: mockUseMutation,
  useQuery: mockUseQuery,
}));

vi.mock('sonner', () => ({
  toast: {
    error: vi.fn(),
    success: vi.fn(),
  },
}));

describe('AgentWorkspaceShell', () => {
  it('renders a missing state and skips dependent queries for a null job', () => {
    mockUseQuery.mockImplementation((query) =>
      getFunctionName(query) === 'agentJobs:get' ? null : undefined,
    );

    render(<AgentWorkspaceShell jobId={'job-1' as never} />);

    expect(
      screen.getByText('This workspace was not found.'),
    ).toBeInTheDocument();
    expect(
      mockUseQuery.mock.calls.map(([query]) => getFunctionName(query)),
    ).toEqual([
      'agentJobs:get',
      'agentJobs:listMessages',
      'agentJobs:listEvents',
      'agentJobs:listWorkspaceChanges',
      'agentJobs:listInteractionRequests',
      'agentJobs:getWorkspaceUiState',
    ]);
    expect(mockUseQuery.mock.calls[0]?.[1]).toEqual({ jobId: 'job-1' });
    for (let call = 2; call <= 6; call += 1) {
      expect(mockUseQuery.mock.calls[call - 1]?.[1]).toBe('skip');
    }
  });
});
