import {
  Body,
  Controller,
  HttpCode,
  HttpStatus,
  Post,
  UseGuards,
} from '@nestjs/common';
import { AllowAuth } from '../common/decorators/allow-auth.decorator';
import { RequireScopes } from '../common/decorators/require-scopes.decorator';
import { ServiceCredentialGuard } from '../common/guards/service-credential/service-credential.guard';
import { AutomationsService } from './automations.service';
import { IngestAutomationEventDto } from './dto/ingest-automation-event.dto';
import { ScheduleWaitDto } from './dto/schedule-wait.dto';
import { AutomationRateLimitGuard } from './guards/automation-rate-limit.guard';

@Controller('automations')
export class AutomationsController {
  constructor(private readonly automationsService: AutomationsService) {}

  @Post('events')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:automations:write')
  @UseGuards(AutomationRateLimitGuard, ServiceCredentialGuard)
  @HttpCode(HttpStatus.ACCEPTED)
  ingestEvent(@Body() dto: IngestAutomationEventDto) {
    return this.automationsService.recordAndIngest(dto);
  }

  @Post('wait')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:automations:write')
  // Sem rate-limit por IP (server-to-server confiável, já autenticado por service
  // key): uma rajada de esperas vencendo não pode virar 429 e perder o timer.
  @UseGuards(ServiceCredentialGuard)
  @HttpCode(HttpStatus.ACCEPTED)
  scheduleWait(@Body() dto: ScheduleWaitDto) {
    return this.automationsService.scheduleWait(dto);
  }

  @Post('sync')
  @AllowAuth(['service_key'])
  @RequireScopes('bff:automations:write')
  @UseGuards(ServiceCredentialGuard)
  @HttpCode(HttpStatus.ACCEPTED)
  syncAutomation(@Body() body: { id?: string }) {
    return { accepted: true, id: body.id ?? null };
  }
}
