import{logger as e}from"../logger/index.mjs";import{GenericError as t}from"../utils/errors/ErrorsClass.mjs";import{getOrganizationById as n,updatePlan as r}from"./organization.service.mjs";import{getUserById as i}from"./user.service.mjs";import{sendEmail as a}from"./email.service.mjs";import{retrievePlanInformation as o}from"../utils/plan.mjs";import s from"stripe";const c=async(n,a,c,l,u,d)=>{let f=new s(process.env.STRIPE_SECRET_KEY),p=await i(l);if(!p)throw new t(`USER_NOT_FOUND`,{userId:l});String(p.customerId)!==c&&(p.customerId=c,await p.save());let m=o(a),h=await f.subscriptions.list({customer:c,status:`active`,limit:1});if(h.data.length>=1){let e=h.data.filter(e=>e.id!==n);for(let t of e)await f.subscriptions.cancel(t.id)}let g=await r(u,{creatorId:p.id,priceId:a,customerId:c,subscriptionId:n,type:m.type,period:m.period,status:d});if(!g)throw new t(`ORGANIZATION_UPDATE_FAILED`,{organizationId:u.id});return e.info(`Plan updated for organization ${u.id} - ${m.type} - ${m.period}`),g.plan??null},l=async(i,a)=>{let o=await n(a);if(!o)throw new t(`ORGANIZATION_NOT_FOUND`,{subscriptionId:i});if(!i)throw new t(`NO_SUBSCRIPTION_ID_PROVIDED`);if(!o.plan)throw new t(`ORGANIZATION_PLAN_NOT_FOUND`,{subscriptionId:i,organizationId:o.id});let s=await r(o,{status:`canceled`});if(!s)throw new t(`ORGANIZATION_UPDATE_FAILED`,{organizationId:o.id});return e.info(`Cancelled plan for organization ${s.id} - ${s.plan?.type} - ${s.plan?.period}`),s.plan??null},u=async(o,s,c,l)=>{let u=await n(l);if(!u)throw new t(`ORGANIZATION_NOT_FOUND`,{userId:c,subscriptionId:o});if(!u.plan)throw new t(`ORGANIZATION_PLAN_NOT_FOUND`,{userId:c,subscriptionId:o,organizationId:u.id});let d=await r(u,{status:s,subscriptionId:o});if(!d)throw new t(`ORGANIZATION_UPDATE_FAILED`,{organizationId:u.id});let f=await i(c);if(!f)throw new t(`USER_NOT_FOUND`,{userId:c,subscriptionId:o});e.info(`Updated plan status for organization ${u.id} - Status: ${s}`);let p={to:f.email,username:f.name,email:f.email,planName:u.plan.type,date:new Date().toLocaleDateString(),link:`${process.env.APP_URL}/dashboard`};switch(s){case`active`:await a({...p,type:`subscriptionPaymentSuccess`,organizationName:u.name,subscriptionStartDate:p.date,manageSubscriptionLink:p.link});break;case`canceled`:await a({...p,type:`subscriptionPaymentCancellation`,organizationName:u.name,cancellationDate:p.date,reactivateLink:p.link});break;case`incomplete`:await a({...p,type:`subscriptionPaymentError`,organizationName:u.name,errorDate:p.date,retryPaymentLink:p.link});break;default:e.warn(`Unhandled subscription status: ${s}`)}return d.plan??null},d=async e=>{let t=new s(process.env.STRIPE_SECRET_KEY);try{let n=(await t.coupons.list()).data.find(t=>t.name===e);return n?n.id:null}catch(e){return console.error(`Error retrieving coupon:`,e),null}},f=async(e,t)=>{let n=new s(process.env.STRIPE_SECRET_KEY);try{let r=e.map(e=>n.prices.retrieve(e)),i=await Promise.all(r),a=i.reduce((e,t)=>e+(t.unit_amount??0),0),o=0,s=null;if(t){let e=(await n.coupons.list()).data.find(e=>e.name===t);e&&(e.amount_off?(o=e.amount_off,s=`amount`):e.percent_off&&(o=e.percent_off,s=`percentage`))}let c={};for(let e of i){if(!e.id||!e.unit_amount)continue;let t=e.unit_amount,n=0,r=t;if(s===`percentage`&&o>0)n=t*o/100,r=t-n;else if(s===`amount`&&a>0&&o>0){let e=t/a;n=o*e,r=t-n}r=Math.max(r,0),c[e.id]={originalTotal:t,discountApplied:n,discountType:s,finalTotal:r,currency:e.currency}}return c}catch(e){throw console.error(`Error calculating pricing per priceId:`,e),Error(`Failed to calculate pricing breakdown.`)}};export{c as addOrUpdateSubscription,l as cancelSubscription,u as changeSubscriptionStatus,d as getCouponId,f as getPricing};
//# sourceMappingURL=subscription.service.mjs.map