import { Result } from '@gridpilot/shared/application/Result';
import { RaceCreationResult } from '../../domain/value-objects/RaceCreationResult';
import type { CheckoutServicePort } from '../ports/CheckoutServicePort';
import type { Logger } from '@core/shared/application';

export class CompleteRaceCreationUseCase {
  constructor(private readonly checkoutService: CheckoutServicePort, private readonly logger: Logger) {}

  async execute(sessionId: string): Promise<Result<RaceCreationResult>> {
    this.logger.debug(`Attempting to complete race creation for session ID: ${sessionId}`);
    if (!sessionId || sessionId.trim() === '') {
      this.logger.error('Session ID is required for completing race creation.');
      return Result.err(new Error('Session ID is required'));
    }

    const infoResult = await this.checkoutService.extractCheckoutInfo();
    
    if (infoResult.isErr()) {
      this.logger.error(`Failed to extract checkout info: ${infoResult.unwrapErr().message}`);
      return Result.err(infoResult.unwrapErr());
    }

    const info = infoResult.unwrap();
    this.logger.debug(`Extracted checkout information: ${JSON.stringify(info)}`);

    if (!info.price) {
      this.logger.error('Could not extract price from checkout page.');
      return Result.err(new Error('Could not extract price from checkout page'));
    }

    try {
      const raceCreationResult = RaceCreationResult.create({
        sessionId,
        price: info.price.toDisplayString(),
        timestamp: new Date(),
      });

      this.logger.info(`Race creation completed successfully for session ID: ${sessionId}`);
      return Result.ok(raceCreationResult);
    } catch (error) {
      const err = error instanceof Error ? error : new Error('Unknown error');
      this.logger.error(`Error completing race creation for session ID ${sessionId}: ${err.message}`);
      return Result.err(err);
    }
  }
}