import { Injectable, Logger } from '@nestjs/common';
import { TaskRepository } from '../../infrastructure/repositories/task.repository';
import { RunbookRepository } from '../../infrastructure/repositories/runbook.repository';
import { OpsTask } from '../../domain/entities/ops-task.entity';
import { TaskType } from '../../domain/value-objects/task-type.vo';
import * as crypto from 'crypto';

export interface CreateInspectionTaskInput {
  tenantId: string;
  title: string;
  description?: string;
  targetServers: string[];
  runbookId?: string;
  createdBy: string;
}

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

  constructor(
    private readonly taskRepository: TaskRepository,
    private readonly runbookRepository: RunbookRepository,
  ) {}

  async execute(input: CreateInspectionTaskInput): Promise<OpsTask> {
    this.logger.log(`Creating inspection task: ${input.title}`);

    if (input.runbookId) {
      const runbook = await this.runbookRepository.findById(input.runbookId);
      if (!runbook) {
        throw new Error(`Runbook ${input.runbookId} not found`);
      }
    }

    const task = new OpsTask();
    task.id = crypto.randomUUID();
    task.tenantId = input.tenantId;
    task.type = TaskType.INSPECTION;
    task.title = input.title;
    task.description = input.description;
    task.status = 'pending';
    task.priority = 1;
    task.targetServers = input.targetServers;
    task.runbookId = input.runbookId;
    task.createdBy = input.createdBy;
    task.createdAt = new Date();

    const saved = await this.taskRepository.save(task);
    this.logger.log(`Inspection task created: ${saved.id}`);
    return saved;
  }
}
