import { AutomationSession } from '../../domain/entities/AutomationSession';
import { HostedSessionConfig } from '../../domain/entities/HostedSessionConfig';
import { IAutomationEngine } from '../ports/IAutomationEngine';
import { IBrowserAutomation } from '../ports/IBrowserAutomation';
import { ISessionRepository } from '../ports/ISessionRepository';

export interface SessionDTO {
  sessionId: string;
  state: string;
  currentStep: number;
  config: HostedSessionConfig;
  startedAt?: Date;
  completedAt?: Date;
  errorMessage?: string;
}

export class StartAutomationSessionUseCase {
  constructor(
    private readonly automationEngine: IAutomationEngine,
    private readonly browserAutomation: IBrowserAutomation,
    private readonly sessionRepository: ISessionRepository
  ) {}

  async execute(config: HostedSessionConfig): Promise<SessionDTO> {
    const session = AutomationSession.create(config);

    const validationResult = await this.automationEngine.validateConfiguration(config);
    if (!validationResult.isValid) {
      throw new Error(validationResult.error);
    }

    await this.sessionRepository.save(session);

    return {
      sessionId: session.id,
      state: session.state.value,
      currentStep: session.currentStep.value,
      config: session.config,
      startedAt: session.startedAt,
      completedAt: session.completedAt,
      errorMessage: session.errorMessage,
    };
  }
}