import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { DIContainer } from '../../../..//apps/companion/main/di-container';
import type { HostedSessionConfig } from 'apps/companion/main/automation/domain/types/HostedSessionConfig';
import { StepId } from 'apps/companion/main/automation/domain/value-objects/StepId';

describe('companion start automation - happy path', () => {
  const originalEnv = { ...process.env };

  beforeEach(() => {
    process.env = { ...originalEnv, NODE_ENV: 'test' };
    DIContainer.resetInstance();
  });

  afterEach(async () => {
    const container = DIContainer.getInstance();
    await container.shutdown();
    DIContainer.resetInstance();
    process.env = originalEnv;
  });

  it('creates a non-failed session and does not report browser-not-connected', async () => {
    const container = DIContainer.getInstance();
    const startAutomationUseCase = container.getStartAutomationUseCase();
    const sessionRepository = container.getSessionRepository();
    const automationEngine = container.getAutomationEngine();

    const connectionResult = await container.initializeBrowserConnection();
    expect(connectionResult.success).toBe(true);

    const config: HostedSessionConfig = {
      sessionName: 'Companion integration happy path',
      trackId: 'test-track',
      carIds: ['car-1'],
    };

    const dto = await startAutomationUseCase.execute(config);

    const sessionBefore = await sessionRepository.findById(dto.sessionId);
    expect(sessionBefore).toBeDefined();

    await automationEngine.executeStep(StepId.create(1), config);

    const session = await sessionRepository.findById(dto.sessionId);
    expect(session).toBeDefined();

    const state = session!.state.value as string;
    expect(state).not.toBe('FAILED');

    const errorMessage = session!.errorMessage as string | undefined;
    if (errorMessage) {
      expect(errorMessage).not.toContain('Browser not connected');
    }
  });
});