import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { EngineRegistry } from '../../infrastructure/engines/engine-registry';
import { SessionRepository } from '../../infrastructure/repositories/session.repository';
import { TaskRepository } from '../../infrastructure/repositories/task.repository';
import { TaskStatus } from '../../domain/value-objects/task-status.vo';

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

  constructor(
    private readonly engineRegistry: EngineRegistry,
    private readonly sessionRepository: SessionRepository,
    private readonly taskRepository: TaskRepository,
  ) {}

  async execute(taskId: string): Promise<{ message: string; taskId: string }> {
    const task = await this.taskRepository.findById(taskId);
    if (!task) {
      throw new NotFoundException(`Task ${taskId} not found`);
    }

    const session = await this.sessionRepository.findById(task.sessionId);
    if (!session) {
      throw new NotFoundException(`Session ${task.sessionId} not found`);
    }

    const engine = this.engineRegistry.getActiveEngine();
    await engine.cancelTask(session.id);

    task.status = TaskStatus.CANCELLED;
    task.completedAt = new Date();
    await this.taskRepository.save(task);

    session.status = 'cancelled';
    session.updatedAt = new Date();
    await this.sessionRepository.save(session);

    this.logger.log(`Task ${taskId} cancelled for session ${session.id}`);

    return { message: 'Task cancelled', taskId };
  }
}
