import { Controller, Get, Post, Body, Param, NotFoundException } from '@nestjs/common';
import { TaskRepository } from '../../../infrastructure/repositories/task.repository';
import { OpsTask } from '../../../domain/entities/ops-task.entity';
import * as crypto from 'crypto';

@Controller('api/v1/ops/tasks')
export class TaskController {
  constructor(private readonly taskRepository: TaskRepository) {}

  @Get()
  async listTasks() {
    return this.taskRepository.findAll();
  }

  @Post()
  async createTask(@Body() body: any) {
    const task = new OpsTask();
    task.id = crypto.randomUUID();
    task.tenantId = body.tenantId;
    task.type = body.type;
    task.title = body.title;
    task.description = body.description;
    task.status = 'pending';
    task.priority = body.priority ?? 0;
    task.targetServers = body.targetServers ?? [];
    task.runbookId = body.runbookId;
    task.agentSessionId = body.agentSessionId;
    task.createdBy = body.createdBy;
    task.createdAt = new Date();
    return this.taskRepository.save(task);
  }

  @Get(':id')
  async getTask(@Param('id') id: string) {
    const task = await this.taskRepository.findById(id);
    if (!task) {
      throw new NotFoundException(`Task ${id} not found`);
    }
    return task;
  }
}
