"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var StripeWebhookController_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.StripeWebhookController = void 0;
const common_1 = require("@nestjs/common");
const swagger_1 = require("@nestjs/swagger");
const stripe_service_1 = require("../services/stripe.service");
let StripeWebhookController = StripeWebhookController_1 = class StripeWebhookController {
    constructor(stripeService) {
        this.stripeService = stripeService;
        this.logger = new common_1.Logger(StripeWebhookController_1.name);
    }
    async handleWebhook(req, res, signature) {
        const response = {
            received: false,
        };
        if (!signature) {
            this.logger.warn('Webhook received without signature');
            res.status(common_1.HttpStatus.BAD_REQUEST).json({
                received: false,
                error: 'Missing stripe-signature header',
            });
            return;
        }
        const rawBody = req.rawBody;
        if (!rawBody) {
            this.logger.warn('Webhook received without raw body');
            res.status(common_1.HttpStatus.BAD_REQUEST).json({
                received: false,
                error: 'Missing raw body',
            });
            return;
        }
        try {
            const event = this.stripeService.constructWebhookEvent(rawBody, signature);
            this.logger.log(`Received webhook event: ${event.type} (${event.id})`);
            await this.stripeService.handleWebhookEvent(event);
            response.received = true;
            response.event_type = event.type;
            res.status(common_1.HttpStatus.OK).json(response);
        }
        catch (error) {
            this.logger.error(`Webhook error: ${error.message}`, error.stack);
            if (error.type === 'StripeSignatureVerificationError') {
                res.status(common_1.HttpStatus.BAD_REQUEST).json({
                    received: false,
                    error: 'Invalid signature',
                });
                return;
            }
            res.status(common_1.HttpStatus.INTERNAL_SERVER_ERROR).json({
                received: false,
                error: error.message,
            });
        }
    }
};
exports.StripeWebhookController = StripeWebhookController;
__decorate([
    (0, common_1.Post)(),
    (0, common_1.HttpCode)(common_1.HttpStatus.OK),
    (0, swagger_1.ApiExcludeEndpoint)(),
    (0, swagger_1.ApiOperation)({ summary: 'Handle Stripe webhook events' }),
    (0, swagger_1.ApiHeader)({
        name: 'stripe-signature',
        description: 'Stripe webhook signature',
        required: true,
    }),
    __param(0, (0, common_1.Req)()),
    __param(1, (0, common_1.Res)()),
    __param(2, (0, common_1.Headers)('stripe-signature')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String]),
    __metadata("design:returntype", Promise)
], StripeWebhookController.prototype, "handleWebhook", null);
exports.StripeWebhookController = StripeWebhookController = StripeWebhookController_1 = __decorate([
    (0, swagger_1.ApiTags)('stripe-webhooks'),
    (0, common_1.Controller)('webhooks/stripe'),
    __metadata("design:paramtypes", [stripe_service_1.StripeService])
], StripeWebhookController);
//# sourceMappingURL=stripe-webhook.controller.js.map