import { formatResponse } from "../utils/responseData.mjs";
import { ErrorHandler } from "../utils/errors/ErrorHandler.mjs";
import { sendEmail } from "../services/email.service.mjs";
import { retrievePlanInformation } from "../utils/plan.mjs";
import { cancelSubscription as cancelSubscription$1, getCouponId, getPricing as getPricing$1 } from "../services/subscription.service.mjs";
import { t } from "express-intlayer";
import { Stripe } from "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 = formatResponse({ data: await getPricing$1(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 = new Stripe(process.env.STRIPE_SECRET_KEY);
		const { organization, user } = res.locals;
		const { priceId, promoCode } = req.body;
		if (!organization) {
			ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_NOT_FOUND");
			return;
		}
		if (!user) {
			ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
			return;
		}
		const { period, type } = retrievePlanInformation(priceId);
		if (organization.plan?.subscriptionId && organization.plan?.type === type && organization.plan?.period === period && organization.plan?.status === "active") {
			ErrorHandler.handleGenericErrorResponse(res, "ALREADY_SUBSCRIBED", { organizationId: organization.id });
			return;
		}
		let customerId = organization.plan?.customerId;
		if (!customerId) customerId = (await stripe.customers.create({ metadata: {
			organizationId: String(organization.id),
			userId: String(user.id),
			locale: res.locals.locale
		} })).id;
		const promoCodeId = promoCode ? await getCouponId(promoCode) : null;
		const discounts = promoCodeId ? [{ coupon: promoCodeId }] : [];
		const subscription = await stripe.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) {
			ErrorHandler.handleGenericErrorResponse(res, "SUBSCRIPTION_CREATION_FAILED", {
				user,
				organization,
				priceId
			});
			return;
		}
		const clientSecret = subscription.latest_invoice?.confirmation_secret?.client_secret;
		if (!clientSecret) {
			ErrorHandler.handleGenericErrorResponse(res, "SUBSCRIPTION_CREATION_FAILED", {
				user,
				organization,
				priceId
			});
			return;
		}
		const responseData = formatResponse({ data: {
			subscription,
			clientSecret
		} });
		res.json(responseData);
		return;
	} catch (error) {
		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 = new Stripe(process.env.STRIPE_SECRET_KEY);
	try {
		const { organization, user } = res.locals;
		if (!organization) {
			ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_NOT_FOUND");
			return;
		}
		if (!user) {
			ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
			return;
		}
		if (!organization.plan?.subscriptionId) {
			ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_PLAN_NOT_FOUND");
			return;
		}
		await stripe.subscriptions.cancel(organization.plan.subscriptionId);
		const plan = await cancelSubscription$1(organization.plan.subscriptionId, String(organization.id));
		if (!plan) {
			ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_PLAN_NOT_FOUND");
			return;
		}
		const formattedPlan = formatResponse({
			message: t({
				en: "Subscription cancelled successfully",
				fr: "Souscription annulée avec succès",
				es: "Suscripción cancelada con éxito"
			}),
			description: 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 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) {
		ErrorHandler.handleAppErrorResponse(res, error);
	}
};

//#endregion
export { cancelSubscription, getPricing, getSubscription };
//# sourceMappingURL=stripe.controller.mjs.map