import {
  Body,
  Controller,
  HttpCode,
  HttpStatus,
  Logger,
  Post,
} from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { Public } from "@edr/api-common";
import { PaymentEventDto, MarkPaidResponseDto } from "./internal-payment.dto";
import { PaymentService } from "./payment.service";

/**
 * Consumer side of the payment microservice's outbox relay.
 * WARNING: currently unauthenticated — anyone who can reach the API can mark
 * payments as paid. Re-add ServiceAuthGuard before exposing beyond a trusted network.
 * Idempotent by design — the relay delivers at-least-once, so duplicates must be harmless.
 * Becomes a queue consumer via PaymentEventsConsumer when RabbitMQ is available;
 * this HTTP endpoint remains as a transport-agnostic fallback.
 */
@ApiTags("Internal Payments")
@Public()
@Controller("internal/payments")
export class InternalPaymentController {
  private readonly logger = new Logger(InternalPaymentController.name);
  constructor(private readonly paymentService: PaymentService) { }

  @Post("mark-paid")
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary:
      "Apply a payment.succeeded / payment.failed event from the payment service (idempotent)",
  })
  async markPaid(@Body() event: PaymentEventDto): Promise<MarkPaidResponseDto> {
    this.logger.log(`Marking payment ${event} as PAID`);
    return this.paymentService.handlePaymentEvent(event);
  }
}
