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 "fastify-intlayer";
import { Stripe } from "stripe";

//#region src/controllers/stripe.controller.ts
/**
* Simulate pricing for a given set of prices and a promotion code.
*
* @param request - The request object containing the price IDs and promotion code.
* @param reply - The response object to send the simulated pricing result.
*/
const getPricing = async (request, reply) => {
	const { priceIds, promoCode } = request.body;
	const formattedPricingResult = formatResponse({ data: await getPricing$1(priceIds, promoCode) });
	reply.code(200).send(formattedPricingResult);
};
/**
* Handles subscription creation or update with Stripe and returns a ClientSecret.
*/
const getSubscription = async (request, reply) => {
	try {
		const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
		const { organization, user } = request.locals || {};
		const { priceId, promoCode } = request.body;
		if (!organization) return ErrorHandler.handleGenericErrorResponse(reply, "ORGANIZATION_NOT_FOUND");
		if (!user) return ErrorHandler.handleGenericErrorResponse(reply, "USER_NOT_FOUND");
		const { period, type } = retrievePlanInformation(priceId);
		if (organization.plan?.subscriptionId && organization.plan?.type === type && organization.plan?.period === period && organization.plan?.status === "active") return ErrorHandler.handleGenericErrorResponse(reply, "ALREADY_SUBSCRIBED", { organizationId: organization.id });
		let customerId = organization.plan?.customerId;
		if (!customerId) customerId = (await stripe.customers.create({ metadata: {
			organizationId: String(organization.id),
			userId: String(user.id),
			locale: request.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) return ErrorHandler.handleGenericErrorResponse(reply, "SUBSCRIPTION_CREATION_FAILED", {
			user,
			organization,
			priceId
		});
		const clientSecret = subscription.latest_invoice?.confirmation_secret?.client_secret;
		if (!clientSecret) return ErrorHandler.handleGenericErrorResponse(reply, "SUBSCRIPTION_CREATION_FAILED", {
			user,
			organization,
			priceId
		});
		const responseData = formatResponse({ data: {
			subscription,
			clientSecret
		} });
		return reply.send(responseData);
	} catch (error) {
		return ErrorHandler.handleAppErrorResponse(reply, error);
	}
};
/**
* Cancels a subscription for an organization.
*/
const cancelSubscription = async (_request, reply) => {
	const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
	try {
		const { organization, user } = _request.locals || {};
		if (!organization) return ErrorHandler.handleGenericErrorResponse(reply, "ORGANIZATION_NOT_FOUND");
		if (!user) return ErrorHandler.handleGenericErrorResponse(reply, "USER_NOT_FOUND");
		if (!organization.plan?.subscriptionId) return ErrorHandler.handleGenericErrorResponse(reply, "ORGANIZATION_PLAN_NOT_FOUND");
		await stripe.subscriptions.cancel(organization.plan.subscriptionId);
		const plan = await cancelSubscription$1(organization.plan.subscriptionId, String(organization.id));
		if (!plan) return ErrorHandler.handleGenericErrorResponse(reply, "ORGANIZATION_PLAN_NOT_FOUND");
		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
		});
		reply.send(formattedPlan);
		await sendEmail({
			type: "subscriptionPaymentCancellation",
			to: user.email,
			email: user.email,
			cancellationDate: (/* @__PURE__ */ new Date()).toLocaleDateString(),
			reactivateLink: `${process.env.APP_URL}/pricing`,
			username: user.name,
			organizationName: organization.name,
			planName: plan.type
		});
	} catch (error) {
		return ErrorHandler.handleAppErrorResponse(reply, error);
	}
};

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