import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { StandingOrderRepository } from '../../infrastructure/repositories/standing-order.repository';
import { StandingOrderExecutorService } from '../../domain/services/standing-order-executor.service';
import { StandingOrderExecution } from '../../domain/entities/standing-order-execution.entity';

@Injectable()
export class ExecuteStandingOrderUseCase {
  private readonly logger = new Logger(ExecuteStandingOrderUseCase.name);

  constructor(
    private readonly standingOrderRepository: StandingOrderRepository,
    private readonly executorService: StandingOrderExecutorService,
  ) {}

  async execute(
    orderId: string,
    triggerContext?: Record<string, unknown>,
  ): Promise<StandingOrderExecution> {
    const order = await this.standingOrderRepository.findById(orderId);
    if (!order) {
      throw new NotFoundException(`Standing order ${orderId} not found`);
    }

    if (order.status !== 'active') {
      throw new Error(`Standing order ${orderId} is not active (current status: ${order.status})`);
    }

    this.logger.log(`Manually executing standing order: ${order.name} (${orderId})`);

    const context = {
      triggerType: 'manual',
      ...triggerContext,
    };

    return this.executorService.executeOrder(order, context);
  }
}
