import{logger as e}from"../logger/index.mjs";import{GenericError as t}from"../utils/errors/ErrorsClass.mjs";import{getOrganizationById as n}from"../services/organization.service.mjs";import{getUserById as r}from"../services/user.service.mjs";import{sendEmail as i}from"../services/email.service.mjs";import{addOrUpdateSubscription as a,cancelSubscription as o,changeSubscriptionStatus as s}from"../services/subscription.service.mjs";import{Stripe as c}from"stripe";const l=async(l,u)=>{let d=new c(process.env.STRIPE_SECRET_KEY),f=process.env.STRIPE_WEBHOOK_SECRET,p=l.headers[`stripe-signature`],m;try{m=d.webhooks.constructEvent(l.body,p,f)}catch(e){u.status(400).send(`Webhook Error: ${e.message}`);return}let h=async e=>(await d.customers.retrieve(e)).metadata,g=async(e,o)=>{let{id:s,customer:c}=e,l=e.items.data[0]?.price?.id;if(!c)throw new t(`STRIPE_SUBSCRIPTION_NO_CUSTOMER`);let d=c,{locale:f,userId:p,organizationId:m}=await h(d);f&&(u.locals.locales=f);let g=await n(m);if(!g)throw new t(`ORGANIZATION_NOT_FOUND`);let _=await r(p);if(!_)throw new t(`USER_NOT_FOUND`);let v=o??e.status;await a(s,l,d,p,g,v),v===`active`&&await i({type:`subscriptionPaymentSuccess`,to:_.email,email:_.email,subscriptionStartDate:new Date().toLocaleDateString(),manageSubscriptionLink:`${process.env.APP_URL}/organization`,username:_.name,organizationName:g.name,planName:g.plan?.type??`Unknown`}),v===`canceled`&&await i({type:`subscriptionPaymentCancellation`,to:_.email,email:_.email,cancellationDate:new Date(e.current_period_end*1e3).toLocaleDateString(),reactivateLink:`${process.env.APP_URL}/pricing`,username:_.name,organizationName:g.name,planName:g.plan?.type??`Unknown`})},_=async(t,r)=>{let i=typeof t.subscription==`string`?t.subscription:t.subscription?.id;if(!i){e.warn(`Subscription ID is undefined in invoice.`);return}let a=await n((await d.subscriptions.retrieve(i)).metadata.organizationId);a.plan?.subscriptionId&&a.plan.subscriptionId!==i&&await d.subscriptions.cancel(i);let o=t.customer,{locale:c,userId:l,organizationId:f}=await h(o);c&&(u.locals.locales=c),await s(i,r,l,f)};try{switch(e.info(`Triggered event type ${m.type}`),m.type){case`customer.subscription.created`:e.info(`Handled event type ${m.type}`),await g(m.data.object);break;case`customer.subscription.updated`:e.info(`Handled event type ${m.type}`),await g(m.data.object);break;case`customer.subscription.deleted`:{e.info(`Handled event type ${m.type}`);let t=m.data.object,n=t.customer,{locale:r,organizationId:i}=await h(n);r&&(u.locals.locales=r),await o(t.id,i);break}case`invoice.payment_succeeded`:e.info(`Handled event type ${m.type}`),await _(m.data.object,`active`);break;case`invoice.payment_failed`:e.info(`Handled event type ${m.type}`),await _(m.data.object,`incomplete`);break;default:e.info(`Unhandled event type ${m.type}`)}u.send()}catch(t){e.error(`Error handling event ${m.type}: ${t.message}`),u.status(500).send(`Server Error`)}};export{l as stripeWebhook};
//# sourceMappingURL=stripe.webhook.mjs.map