import { Controller, Get, Post, Put, Body, Param, Query, NotFoundException } from '@nestjs/common';
import { AlertRuleRepository } from '../../../infrastructure/repositories/alert-rule.repository';
import { AlertEventRepository } from '../../../infrastructure/repositories/alert-event.repository';
import { AlertRule } from '../../../domain/entities/alert-rule.entity';
import * as crypto from 'crypto';

@Controller('api/v1/monitor/alerts')
export class AlertController {
  constructor(
    private readonly alertRuleRepository: AlertRuleRepository,
    private readonly alertEventRepository: AlertEventRepository,
  ) {}

  @Get('rules')
  async listRules() {
    return this.alertRuleRepository.findAll();
  }

  @Post('rules')
  async createRule(@Body() body: any) {
    const rule = new AlertRule();
    rule.id = crypto.randomUUID();
    rule.tenantId = body.tenantId;
    rule.name = body.name;
    rule.metricType = body.metricType;
    rule.condition = body.condition;
    rule.severity = body.severity;
    rule.targetServers = body.targetServers;
    rule.runbookId = body.runbookId;
    rule.isActive = body.isActive ?? true;
    rule.createdAt = new Date();
    return this.alertRuleRepository.save(rule);
  }

  @Get('events')
  async listEvents(@Query('status') status?: string) {
    if (status) {
      return this.alertEventRepository.findByStatus(status);
    }
    return this.alertEventRepository.findAll();
  }

  @Put('events/:id/acknowledge')
  async acknowledgeEvent(@Param('id') id: string) {
    const event = await this.alertEventRepository.findById(id);
    if (!event) {
      throw new NotFoundException(`Alert event ${id} not found`);
    }
    event.status = 'acknowledged';
    event.acknowledgedBy = 'user';
    return this.alertEventRepository.save(event);
  }
}
