const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const require_logger_index = require('../logger/index.cjs');
const require_utils_errors_ErrorsClass = require('../utils/errors/ErrorsClass.cjs');
const require_services_organization_service = require('../services/organization.service.cjs');
const require_services_user_service = require('../services/user.service.cjs');
const require_services_email_service = require('../services/email.service.cjs');
const require_services_subscription_service = require('../services/subscription.service.cjs');
let stripe = require("stripe");

//#region src/webhooks/stripe.webhook.ts
/**
* Stripe webhook handler for processing subscription and invoice events.
* @param req - Express request object.
* @param res - Express response object.
*/
const stripeWebhook = async (req, res) => {
	const stripe$1 = new stripe.Stripe(process.env.STRIPE_SECRET_KEY);
	const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
	const sig = req.headers["stripe-signature"];
	let event;
	try {
		event = stripe$1.webhooks.constructEvent(req.body, sig, endpointSecret);
	} catch (err) {
		res.status(400).send(`Webhook Error: ${err.message}`);
		return;
	}
	const extractMetadata = async (customerId) => {
		return (await stripe$1.customers.retrieve(customerId)).metadata;
	};
	const handleSubscriptionEvent = async (subscription, statusOverride) => {
		const { id: subscriptionId, customer } = subscription;
		const priceId = subscription.items.data[0]?.price?.id;
		if (!customer) throw new require_utils_errors_ErrorsClass.GenericError("STRIPE_SUBSCRIPTION_NO_CUSTOMER");
		const customerId = customer;
		const { locale, userId, organizationId } = await extractMetadata(customerId);
		if (locale) res.locals.locales = locale;
		const organization = await require_services_organization_service.getOrganizationById(organizationId);
		if (!organization) throw new require_utils_errors_ErrorsClass.GenericError("ORGANIZATION_NOT_FOUND");
		const user = await require_services_user_service.getUserById(userId);
		if (!user) throw new require_utils_errors_ErrorsClass.GenericError("USER_NOT_FOUND");
		const status = statusOverride ?? subscription.status;
		await require_services_subscription_service.addOrUpdateSubscription(subscriptionId, priceId, customerId, userId, organization, status);
		if (status === "active") await require_services_email_service.sendEmail({
			type: "subscriptionPaymentSuccess",
			to: user.email,
			email: user.email,
			subscriptionStartDate: (/* @__PURE__ */ new Date()).toLocaleDateString(),
			manageSubscriptionLink: `${process.env.CLIENT_URL}/dashboard/organization`,
			username: user.name,
			organizationName: organization.name,
			planName: organization.plan?.type ?? "Unknown"
		});
		if (status === "canceled") await require_services_email_service.sendEmail({
			type: "subscriptionPaymentCancellation",
			to: user.email,
			email: user.email,
			cancellationDate: (/* @__PURE__ */ new Date(subscription.current_period_end * 1e3)).toLocaleDateString(),
			reactivateLink: `${process.env.CLIENT_URL}/pricing`,
			username: user.name,
			organizationName: organization.name,
			planName: organization.plan?.type ?? "Unknown"
		});
	};
	const handleInvoiceEvent = async (invoice, status) => {
		const subscriptionId = typeof invoice.subscription === "string" ? invoice.subscription : invoice.subscription?.id;
		if (!subscriptionId) {
			require_logger_index.logger.warn("Subscription ID is undefined in invoice.");
			return;
		}
		const organization = await require_services_organization_service.getOrganizationById((await stripe$1.subscriptions.retrieve(subscriptionId)).metadata.organizationId);
		if (organization.plan?.subscriptionId && organization.plan.subscriptionId !== subscriptionId) await stripe$1.subscriptions.cancel(subscriptionId);
		const customerId = invoice.customer;
		const { locale, userId, organizationId } = await extractMetadata(customerId);
		if (locale) res.locals.locales = locale;
		await require_services_subscription_service.changeSubscriptionStatus(subscriptionId, status, userId, organizationId);
	};
	try {
		require_logger_index.logger.info(`Triggered event type ${event.type}`);
		switch (event.type) {
			case "customer.subscription.created":
				require_logger_index.logger.info(`Handled event type ${event.type}`);
				await handleSubscriptionEvent(event.data.object);
				break;
			case "customer.subscription.updated":
				require_logger_index.logger.info(`Handled event type ${event.type}`);
				await handleSubscriptionEvent(event.data.object);
				break;
			case "customer.subscription.deleted": {
				require_logger_index.logger.info(`Handled event type ${event.type}`);
				const subscription = event.data.object;
				const customerId = subscription.customer;
				const { locale, organizationId } = await extractMetadata(customerId);
				if (locale) res.locals.locales = locale;
				await require_services_subscription_service.cancelSubscription(subscription.id, organizationId);
				break;
			}
			case "invoice.payment_succeeded":
				require_logger_index.logger.info(`Handled event type ${event.type}`);
				await handleInvoiceEvent(event.data.object, "active");
				break;
			case "invoice.payment_failed":
				require_logger_index.logger.info(`Handled event type ${event.type}`);
				await handleInvoiceEvent(event.data.object, "incomplete");
				break;
			default: require_logger_index.logger.info(`Unhandled event type ${event.type}`);
		}
		res.send();
	} catch (error) {
		require_logger_index.logger.error(`Error handling event ${event.type}: ${error.message}`);
		res.status(500).send("Server Error");
	}
};

//#endregion
exports.stripeWebhook = stripeWebhook;
//# sourceMappingURL=stripe.webhook.cjs.map