const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const require_utils_responseData = require('../utils/responseData.cjs');
const require_utils_errors_ErrorHandler = require('../utils/errors/ErrorHandler.cjs');
const require_services_email_service = require('../services/email.service.cjs');
const require_utils_plan = require('../utils/plan.cjs');
const require_services_subscription_service = require('../services/subscription.service.cjs');
let express_intlayer = require("express-intlayer");
let stripe = require("stripe");

//#region src/controllers/stripe.controller.ts
/**
* Simulate pricing for a given set of prices and a promotion code.
*
* @param req - The request object containing the price IDs and promotion code.
* @param res - The response object to send the simulated pricing result.
*/
const getPricing = async (req, res) => {
	const { priceIds, promoCode } = req.body;
	const formattedPricingResult = require_utils_responseData.formatResponse({ data: await require_services_subscription_service.getPricing(priceIds, promoCode) });
	res.status(200).json(formattedPricingResult);
};
/**
* Handles subscription creation or update with Stripe and returns a ClientSecret.
* @param req - Express request object.
* @param res - Express response object.
*/
const getSubscription = async (req, res) => {
	try {
		const stripe$1 = new stripe.Stripe(process.env.STRIPE_SECRET_KEY);
		const { organization, user } = res.locals;
		const { priceId, promoCode } = req.body;
		if (!organization) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_NOT_FOUND");
			return;
		}
		if (!user) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
			return;
		}
		const { period, type } = require_utils_plan.retrievePlanInformation(priceId);
		if (organization.plan?.subscriptionId && organization.plan?.type === type && organization.plan?.period === period && organization.plan?.status === "active") {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "ALREADY_SUBSCRIBED", { organizationId: organization.id });
			return;
		}
		let customerId = organization.plan?.customerId;
		if (!customerId) customerId = (await stripe$1.customers.create({ metadata: {
			organizationId: String(organization.id),
			userId: String(user.id),
			locale: res.locals.locale
		} })).id;
		const promoCodeId = promoCode ? await require_services_subscription_service.getCouponId(promoCode) : null;
		const discounts = promoCodeId ? [{ coupon: promoCodeId }] : [];
		const subscription = await stripe$1.subscriptions.create({
			customer: customerId,
			items: [{ price: priceId }],
			expand: ["latest_invoice.confirmation_secret"],
			payment_settings: { payment_method_types: ["card"] },
			payment_behavior: "default_incomplete",
			discounts
		});
		if (!subscription) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "SUBSCRIPTION_CREATION_FAILED", {
				user,
				organization,
				priceId
			});
			return;
		}
		const clientSecret = subscription.latest_invoice?.confirmation_secret?.client_secret;
		if (!clientSecret) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "SUBSCRIPTION_CREATION_FAILED", {
				user,
				organization,
				priceId
			});
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: {
			subscription,
			clientSecret
		} });
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Cancels a subscription for an organization.
* @param _req - Express request object.
* @param res - Express response object.
*/
const cancelSubscription = async (_req, res) => {
	const stripe$1 = new stripe.Stripe(process.env.STRIPE_SECRET_KEY);
	try {
		const { organization, user } = res.locals;
		if (!organization) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_NOT_FOUND");
			return;
		}
		if (!user) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
			return;
		}
		if (!organization.plan?.subscriptionId) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_PLAN_NOT_FOUND");
			return;
		}
		await stripe$1.subscriptions.cancel(organization.plan.subscriptionId);
		const plan = await require_services_subscription_service.cancelSubscription(organization.plan.subscriptionId, String(organization.id));
		if (!plan) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_PLAN_NOT_FOUND");
			return;
		}
		const formattedPlan = require_utils_responseData.formatResponse({
			message: (0, express_intlayer.t)({
				en: "Subscription cancelled successfully",
				fr: "Souscription annulée avec succès",
				es: "Suscripción cancelada con éxito"
			}),
			description: (0, express_intlayer.t)({
				en: "Your subscription has been cancelled successfully",
				fr: "Votre souscription a été annulée avec succès",
				es: "Su suscripción ha sido cancelada con éxito"
			}),
			data: plan
		});
		res.json(formattedPlan);
		await require_services_email_service.sendEmail({
			type: "subscriptionPaymentCancellation",
			to: user.email,
			email: user.email,
			cancellationDate: (/* @__PURE__ */ new Date()).toLocaleDateString(),
			reactivateLink: `${process.env.CLIENT_URL}/pricing`,
			username: user.name,
			organizationName: organization.name,
			planName: plan.type
		});
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
	}
};

//#endregion
exports.cancelSubscription = cancelSubscription;
exports.getPricing = getPricing;
exports.getSubscription = getSubscription;
//# sourceMappingURL=stripe.controller.cjs.map