import type { AsyncUseCase } from '@core/shared/application';
import type { Logger } from '@core/shared/application';
import { AutomationSession } from '../../domain/entities/AutomationSession';
import type { HostedSessionConfig } from '../../domain/types/HostedSessionConfig';
import { AutomationEnginePort } from '../ports/AutomationEnginePort';
import type { IBrowserAutomation } from '../ports/ScreenAutomationPort';
import { SessionRepositoryPort } from '../ports/SessionRepositoryPort';
import type { SessionDTO } from '../dto/SessionDTO';

export class StartAutomationSessionUseCase
  implements AsyncUseCase<HostedSessionConfig, SessionDTO> {
  constructor(
    private readonly automationEngine: AutomationEnginePort,
    private readonly browserAutomation: IBrowserAutomation,
    private readonly sessionRepository: SessionRepositoryPort,
    private readonly logger: Logger
  ) {}

  async execute(config: HostedSessionConfig): Promise<SessionDTO> {
    this.logger.debug('Starting automation session execution', { config });

    const session = AutomationSession.create(config);
    this.logger.info(`Automation session created with ID: ${session.id}`);

    const validationResult = await this.automationEngine.validateConfiguration(config);
    if (!validationResult.isValid) {
      this.logger.warn('Automation session configuration validation failed', { config, error: validationResult.error });
      throw new Error(validationResult.error);
    }
    this.logger.debug('Automation session configuration validated successfully.');

    await this.sessionRepository.save(session);
    this.logger.info(`Automation session with ID: ${session.id} saved to repository.`);

    const dto: SessionDTO = {
      sessionId: session.id,
      state: session.state.value,
      currentStep: session.currentStep.value,
      config: session.config,
      ...(session.startedAt ? { startedAt: session.startedAt } : {}),
      ...(session.completedAt ? { completedAt: session.completedAt } : {}),
      ...(session.errorMessage ? { errorMessage: session.errorMessage } : {}),
    };

    this.logger.debug('Automation session executed successfully, returning DTO.', { dto });
    return dto;
  }
}