import {
  BadRequestException,
  Controller,
  Headers,
  Post,
  Req,
} from '@nestjs/common';
import { SkipThrottle } from '@nestjs/throttler';
import type { FastifyRequest } from 'fastify';

import { Public } from '../../auth/decorators/current-user.decorator';

import { StripeWebhookService } from './stripe-webhook.service';

@Controller('webhooks/stripe')
@SkipThrottle()
export class StripeWebhookController {
  constructor(private readonly stripe: StripeWebhookService) {}

  @Public()
  @Post()
  handleWebhook(
    @Req() request: FastifyRequest & { rawBody?: string },
    @Headers('stripe-signature') signature?: string,
  ) {
    const rawBody = request.rawBody;
    if (!rawBody) {
      throw new BadRequestException('Missing raw request body for Stripe webhook');
    }

    return this.stripe.handleWebhook(rawBody, signature);
  }
}
