import { Controller, Get, Post, Put, Delete, Body, Param, NotFoundException } from '@nestjs/common';
import { RunbookRepository } from '../../../infrastructure/repositories/runbook.repository';
import { Runbook } from '../../../domain/entities/runbook.entity';
import * as crypto from 'crypto';

@Controller('api/v1/ops/runbooks')
export class RunbookController {
  constructor(private readonly runbookRepository: RunbookRepository) {}

  @Get()
  async listRunbooks() {
    return this.runbookRepository.findAll();
  }

  @Post()
  async createRunbook(@Body() body: any) {
    const runbook = new Runbook();
    runbook.id = crypto.randomUUID();
    runbook.tenantId = body.tenantId;
    runbook.name = body.name;
    runbook.description = body.description;
    runbook.triggerType = body.triggerType ?? 'manual';
    runbook.promptTemplate = body.promptTemplate;
    runbook.allowedTools = body.allowedTools ?? [];
    runbook.maxRiskLevel = body.maxRiskLevel ?? 1;
    runbook.autoApprove = body.autoApprove ?? false;
    runbook.isActive = true;
    runbook.createdAt = new Date();
    return this.runbookRepository.save(runbook);
  }

  @Put(':id')
  async updateRunbook(@Param('id') id: string, @Body() body: any) {
    const runbook = await this.runbookRepository.findById(id);
    if (!runbook) {
      throw new NotFoundException(`Runbook ${id} not found`);
    }
    Object.assign(runbook, body);
    return this.runbookRepository.save(runbook);
  }

  @Delete(':id')
  async deleteRunbook(@Param('id') id: string) {
    const runbook = await this.runbookRepository.findById(id);
    if (!runbook) {
      throw new NotFoundException(`Runbook ${id} not found`);
    }
    await this.runbookRepository.remove(runbook);
    return { message: 'Runbook deleted', id };
  }
}
