import { render, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter, Outlet } from 'react-router-dom';
import App from '@/App';
import { useAuthStore } from '@/stores/auth';
import { useProviderStore } from '@/stores/providers';
import { useSettingsStore } from '@/stores/settings';
import { useUserSyncStore } from '@/stores/user-sync';

vi.mock('@/components/layout/MainLayout', () => ({
  MainLayout: () => <Outlet />,
}));

vi.mock('@/pages/AiHardware', () => ({
  AiHardware: () => <div>Robot workspace</div>,
}));

vi.mock('@/pages/ImageCanvas', () => ({
  ImageCanvas: () => <div>Canvas workspace</div>,
}));

vi.mock('@/pages/Chat', () => ({
  Chat: () => <div>Programming workspace</div>,
}));

describe('App programming provider initialization gate', () => {
  const initProviders = vi.fn();

  beforeEach(() => {
    vi.clearAllMocks();
    window.electron.imageWorkspaceLocalDevelopment = false;
    useSettingsStore.setState({
      setupComplete: true,
      init: vi.fn(),
    });
    useProviderStore.setState({ init: initProviders });
    useAuthStore.setState({
      initialized: true,
      accessToken: 'access-token',
      expiresAt: Date.now() + 60_000,
      user: {
        username: 'robot-tester',
        userId: '1',
        tenantId: null,
        deptId: null,
        authorities: [],
      },
      init: vi.fn(),
    });
    useUserSyncStore.setState({ bootstrap: vi.fn().mockResolvedValue(undefined) });
  });

  async function renderAt(pathname: string) {
    render(
      <MemoryRouter initialEntries={[pathname]}>
        <App />
      </MemoryRouter>,
    );
    await waitFor(() => expect(useSettingsStore.getState().init).toHaveBeenCalled());
  }

  it.each(['/ai-hardware', '/image-canvas', '/module-select'])(
    'does not initialize programming providers at %s',
    async (pathname) => {
      await renderAt(pathname);

      expect(initProviders).not.toHaveBeenCalled();
    },
  );

  it('initializes programming providers at the explicit programming route', async () => {
    await renderAt('/opencode-chat');

    await waitFor(() => expect(initProviders).toHaveBeenCalledTimes(1));
  });
});
