import{formatResponse as e}from"../utils/responseData.mjs";import{ErrorHandler as t}from"../utils/errors/ErrorHandler.mjs";import{sendEmail as n}from"../services/email.service.mjs";import{retrievePlanInformation as r}from"../utils/plan.mjs";import{cancelSubscription as i,getCouponId as a,getPricing as o}from"../services/subscription.service.mjs";import{t as s}from"fastify-intlayer";import{Stripe as c}from"stripe";const l=async(t,n)=>{let{priceIds:r,promoCode:i}=t.body,a=e({data:await o(r,i)});n.code(200).send(a)},u=async(n,i)=>{try{let o=new c(process.env.STRIPE_SECRET_KEY),{organization:s,user:l}=n.locals||{},{priceId:u,promoCode:d}=n.body;if(!s)return t.handleGenericErrorResponse(i,`ORGANIZATION_NOT_FOUND`);if(!l)return t.handleGenericErrorResponse(i,`USER_NOT_FOUND`);let{period:f,type:p}=r(u);if(s.plan?.subscriptionId&&s.plan?.type===p&&s.plan?.period===f&&s.plan?.status===`active`)return t.handleGenericErrorResponse(i,`ALREADY_SUBSCRIBED`,{organizationId:s.id});let m=s.plan?.customerId;m||=(await o.customers.create({metadata:{organizationId:String(s.id),userId:String(l.id),locale:n.locals.locale}})).id;let h=d?await a(d):null,g=h?[{coupon:h}]:[],_=await o.subscriptions.create({customer:m,items:[{price:u}],expand:[`latest_invoice.confirmation_secret`],payment_settings:{payment_method_types:[`card`]},payment_behavior:`default_incomplete`,discounts:g});if(!_)return t.handleGenericErrorResponse(i,`SUBSCRIPTION_CREATION_FAILED`,{user:l,organization:s,priceId:u});let v=_.latest_invoice?.confirmation_secret?.client_secret;if(!v)return t.handleGenericErrorResponse(i,`SUBSCRIPTION_CREATION_FAILED`,{user:l,organization:s,priceId:u});let y=e({data:{subscription:_,clientSecret:v}});return i.send(y)}catch(e){return t.handleAppErrorResponse(i,e)}},d=async(r,a)=>{let o=new c(process.env.STRIPE_SECRET_KEY);try{let{organization:c,user:l}=r.locals||{};if(!c)return t.handleGenericErrorResponse(a,`ORGANIZATION_NOT_FOUND`);if(!l)return t.handleGenericErrorResponse(a,`USER_NOT_FOUND`);if(!c.plan?.subscriptionId)return t.handleGenericErrorResponse(a,`ORGANIZATION_PLAN_NOT_FOUND`);await o.subscriptions.cancel(c.plan.subscriptionId);let u=await i(c.plan.subscriptionId,String(c.id));if(!u)return t.handleGenericErrorResponse(a,`ORGANIZATION_PLAN_NOT_FOUND`);let d=e({message:s({en:`Subscription cancelled successfully`,fr:`Souscription annulée avec succès`,es:`Suscripción cancelada con éxito`}),description:s({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:u});a.send(d),await n({type:`subscriptionPaymentCancellation`,to:l.email,email:l.email,cancellationDate:new Date().toLocaleDateString(),reactivateLink:`${process.env.APP_URL}/pricing`,username:l.name,organizationName:c.name,planName:u.type})}catch(e){return t.handleAppErrorResponse(a,e)}};export{d as cancelSubscription,l as getPricing,u as getSubscription};
//# sourceMappingURL=stripe.controller.mjs.map