'use strict';
import _0x14f4e7 from 'stripe';
import { apiBadRequestError } from '../../../../fd-toolbox/server/web/errors.js';
import { getNow, unixTimestampToDate } from '../../../../fd-toolbox/time/date-time.js';
import { logSeverities } from '../../../../fd-toolbox-core/enums/log-severities.js';
import { envSettingKeys } from '../../../common/infra/env-setting-keys.js';
import { getStringEnvSetting } from '../../../../fd-toolbox/infra/env-functions.js';
import { createError } from '../../../../fd-toolbox/errors/errors.js';
import { stripeSubscriptionBehaviors, stripeErrorConstants, stripeSubscriptionStatuses, billingIntervalsToStripeBillingIntervals } from '../../../common/payments/stripe/stripe-constants.js';
import { addLog } from '../../../../fd-toolbox/server/logging/latest-logs-store.js';
import { isString } from '../../../../fd-toolbox/types/ensure-type.js';
import { billingIntervals } from '../../../meta/core/resources/enums/payment-enums.js';
import { detachPaymentMethod } from '../payments/payments.js';
import { isNullOrUndefined } from '../../../../fd-toolbox/functions/value-checking-functions.js';
import { singleOrUndefined, first } from '../../../../fd-toolbox/server/collections/single-funcs.js';

var __defProp=Object['defineProperty'],__name=(_0x25e0c8,_0x38ca99)=>__defProp(_0x25e0c8,'name',{'value':_0x38ca99,'configurable':!![]});const stripeKey=getStringEnvSetting(envSettingKeys['stripeSecretKey']),centsInADollar=-0x1d19+-0x22a+0x1fa7*0x1;const stripe=new _0x14f4e7(stripeKey,{'apiVersion':'2024-06-20'});function areEnvSettingsConfiguredForPaymentSystem(){return !!stripeKey;}__name(areEnvSettingsConfiguredForPaymentSystem,'areEnvSettingsConfiguredForPaymentSystem');async function findStripeCustomerById(_0x4744bc){return stripe['customers']['retrieve'](_0x4744bc);}__name(findStripeCustomerById,'findStripeCustomerById');async function findStripeCustomerByEmail(_0x8ff290){const _0x148283=await stripe['customers']['list']({'email':_0x8ff290});return _0x148283['data']['length']>-0xe63+-0x2589+0x4*0xcfb?singleOrUndefined(_0x148283['data']):void(-0x23a3+0x1*0x8cc+0x1ad7);}__name(findStripeCustomerByEmail,'findStripeCustomerByEmail');async function createStripeCustomer(_0x5d7a02,_0x591fe7,_0x55dced){return stripe['customers']['create']({'email':_0x591fe7,'name':_0x5d7a02,'metadata':{'workspaceId':_0x55dced}});}__name(createStripeCustomer,'createStripeCustomer');async function hasStripeSubscription(_0x4c3dcf,_0x2752d4){const _0x46354f=await stripe['subscriptions']['list']({'customer':_0x4c3dcf});return _0x46354f['data']['some'](_0x8b9aba=>_0x8b9aba?.['items']?.['data']['some'](_0x35bfd9=>_0x35bfd9['plan']['id']===_0x2752d4));}__name(hasStripeSubscription,'hasStripeSubscription');async function createStripeSubscription(_0x121697,_0x5efa95,_0x49bacb){return stripe['subscriptions']['create']({'customer':_0x121697,'items':[{'price':_0x5efa95}],'payment_behavior':stripeSubscriptionBehaviors['defaultIncomplete'],'expand':[stripeSubscriptionBehaviors['latestInvoicePaymentIntent']],'default_payment_method':_0x49bacb});}__name(createStripeSubscription,'createStripeSubscription');async function createStripeTrialSubscription(_0x3f39b3,_0x3c54f8,_0x5345f3){return stripe['subscriptions']['create']({'customer':_0x3f39b3,'items':[{'price':_0x3c54f8}],'payment_behavior':stripeSubscriptionBehaviors['defaultIncomplete'],'trial_period_days':0x1e,'trial_settings':{'end_behavior':{'missing_payment_method':'create_invoice'}},'default_payment_method':_0x5345f3});}__name(createStripeTrialSubscription,'createStripeTrialSubscription');async function updateCustomerEmailIfNeeded(_0x400f2d,_0x1bb81f){const _0xbdee94=await findStripeCustomerById(_0x400f2d),_0x376566=await stripe['paymentMethods']['retrieve'](_0x1bb81f);!_0xbdee94['deleted']&&_0x376566['billing_details']['email']&&_0xbdee94['email']!==_0x376566['billing_details']['email']&&await changeCustomerEmail(_0x400f2d,_0x376566['billing_details']['email']);}__name(updateCustomerEmailIfNeeded,'updateCustomerEmailIfNeeded');async function attachPaymentMethodToCustomer(_0x49f1c2,_0x4d0a29){await detachAllPaymentMethodsFromCustomer(_0x49f1c2),await stripe['paymentMethods']['attach'](_0x4d0a29,{'customer':_0x49f1c2});}__name(attachPaymentMethodToCustomer,'attachPaymentMethodToCustomer');async function retrievePaymentIntentFromSubscription(_0x3b8516){const _0x5d92ce=await stripe['subscriptions']['retrieve'](_0x3b8516,{'expand':[stripeSubscriptionBehaviors['latestInvoicePaymentIntent']]}),_0x4e511d=_0x5d92ce['latest_invoice'];let _0x161d38;if(typeof _0x4e511d==='object'&&!isNullOrUndefined(_0x4e511d)){const _0x574272=_0x4e511d;if(_0x574272['payment_intent']&&typeof _0x574272['payment_intent']!=='string')_0x161d38=_0x574272['payment_intent'];else throw apiBadRequestError(stripeErrorConstants['paymentIntentError']);}if(typeof _0x4e511d==='string'){const _0x574de3=await stripe['invoices']['retrieve'](_0x4e511d,{'expand':['payment_intent']});if(_0x574de3['payment_intent']&&typeof _0x574de3['payment_intent']!=='string')_0x161d38=_0x574de3['payment_intent'];else throw apiBadRequestError(stripeErrorConstants['paymentIntentError']);}if(!_0x161d38)throw apiBadRequestError(stripeErrorConstants['noLatestInvoice']);return _0x161d38;}__name(retrievePaymentIntentFromSubscription,'retrievePaymentIntentFromSubscription');async function confirmStripePayment(_0x1a8bcc,_0x211f89,_0xb2cc2b){try{return await stripe['paymentIntents']['confirm'](_0x1a8bcc,{'payment_method':_0x211f89});}catch(_0x7bce8c){await cancelStripeSubscriptionById(_0xb2cc2b);throw _0x7bce8c;}}__name(confirmStripePayment,'confirmStripePayment');async function cancelStripeSubscription(_0x5180f3){const _0x766abc=await stripe['subscriptions']['retrieve'](_0x5180f3),_0x4d35a7=getNow(),_0x3f48ff=unixTimestampToDate(_0x766abc['current_period_end']),_0x59d280=_0x766abc['status']===stripeSubscriptionStatuses['active'],_0x14370c=_0x59d280&&_0x3f48ff>_0x4d35a7;let _0x2de70d;return _0x14370c?_0x2de70d=await stripe['subscriptions']['update'](_0x5180f3,{'cancel_at_period_end':!![]}):_0x2de70d=await stripe['subscriptions']['cancel'](_0x5180f3),{'subscriptionId':_0x2de70d['id'],'subscriptionStatus':_0x2de70d['status'],'currentPeriodEndDate':_0x2de70d['current_period_end'],'endDate':_0x14370c?_0x2de70d['cancel_at']:_0x2de70d['canceled_at']};}__name(cancelStripeSubscription,'cancelStripeSubscription');async function instantUpdateStripeSubscription(_0x4a8a60,_0x310567){const _0x1785fb=await stripe['subscriptions']['retrieve'](_0x4a8a60);return stripe['subscriptions']['update'](_0x1785fb['id'],{'items':[{'id':first(_0x1785fb['items']['data'])['id'],'price':_0x310567}],'proration_behavior':'always_invoice'});}__name(instantUpdateStripeSubscription,'instantUpdateStripeSubscription');async function updateStripeSubscriptionWithoutProration(_0x53a6b3,_0x58ae1){const _0x4fcad9=await stripe['subscriptions']['retrieve'](_0x53a6b3);return stripe['subscriptions']['update'](_0x4fcad9['id'],{'items':[{'id':first(_0x4fcad9['items']['data'])['id'],'price':_0x58ae1}],'proration_behavior':stripeSubscriptionBehaviors['noProration'],'billing_cycle_anchor':'unchanged'});}__name(updateStripeSubscriptionWithoutProration,'updateStripeSubscriptionWithoutProration');async function getSubscriptionFromPaymentIntent(_0x3f8f59){const _0x16ca5d=await stripe['paymentIntents']['retrieve'](_0x3f8f59);if(_0x16ca5d['invoice']&&typeof _0x16ca5d['invoice']==='string'){const _0x2910fc=await stripe['invoices']['retrieve'](_0x16ca5d['invoice']);if(_0x2910fc['subscription']&&typeof _0x2910fc['subscription']==='string'){const _0x572199=await stripe['subscriptions']['retrieve'](_0x2910fc['subscription']);return _0x572199['id'];}}throw createError(stripeErrorConstants['noAssociatedSubscription']);}__name(getSubscriptionFromPaymentIntent,'getSubscriptionFromPaymentIntent');async function getStripeSubscriptionData(_0x156812){const _0x2ca19b=await stripe['subscriptions']['retrieve'](_0x156812);return {'status':_0x2ca19b['status'],'currentPeriodEndDate':_0x2ca19b['current_period_end'],'endDate':_0x2ca19b['canceled_at']??void(0xf4*0x13+0x2*-0x11d9+0x1196),'trialEnd':_0x2ca19b['trial_end']};}__name(getStripeSubscriptionData,'getStripeSubscriptionData');async function cancelStripeSubscriptionById(_0x4a078c){return stripe['subscriptions']['cancel'](_0x4a078c);}__name(cancelStripeSubscriptionById,'cancelStripeSubscriptionById');async function processPaymentFailureAndCancelSubscription(_0x35e52e){const _0x1ccd82=_0x35e52e['payment_intent']?.['invoice'];if(!_0x1ccd82||typeof _0x1ccd82!=='string')return;const _0x4494ad=await stripe['invoices']['retrieve'](_0x1ccd82),_0x269012=_0x4494ad['subscription'];_0x269012&&typeof _0x269012==='string'&&await stripe['subscriptions']['cancel'](_0x269012);}__name(processPaymentFailureAndCancelSubscription,'processPaymentFailureAndCancelSubscription');async function getStripePaymentData(_0xacab00){const {currency:_0x3517d7,status:_0xf0a8d2,amount:_0x60e118,payment_method:_0x5f199b}=await stripe['paymentIntents']['retrieve'](_0xacab00);return {'currency':_0x3517d7,'status':_0xf0a8d2,'amount':_0x60e118,'paymentMethodId':_0x5f199b};}__name(getStripePaymentData,'getStripePaymentData');async function getStripeSubscriptionStatus(_0x1009dd){try{const _0x3c4c07=await stripe['subscriptions']['retrieve'](_0x1009dd);return _0x3c4c07['status'];}catch(_0x51b97d){if(_0x51b97d instanceof Error){const _0x43abdc={'severity':logSeverities['warning'],'message':_0x51b97d instanceof _0x14f4e7['errors']['StripeError']?_0x51b97d['type']:_0x51b97d['name'],'errorMessage':_0x51b97d['message'],'stackTrace':_0x51b97d['stack']};addLog(_0x43abdc);}return void(-0x76*-0x15+0x3b*-0x24+-0x6*0x3b);}}__name(getStripeSubscriptionStatus,'getStripeSubscriptionStatus');async function changeStripeProductName(_0x285077,_0x4aed4c){return stripe['products']['update'](_0x285077,{'name':_0x4aed4c});}__name(changeStripeProductName,'changeStripeProductName');async function changeStripeProductStatus(_0x2916b9,_0x1e3170){return stripe['products']['update'](_0x2916b9,{'active':_0x1e3170});}__name(changeStripeProductStatus,'changeStripeProductStatus');async function createStripeProductPricing(_0x28e4ba,_0x2b8693,_0x44d50a,_0x54c188,_0x221fac,_0x2a9e5c=!![]){const _0x38037f=_0x2a9e5c?_0x44d50a*centsInADollar:_0x44d50a;return !_0x221fac||_0x221fac===billingIntervals['lifetime']?stripe['prices']['create']({'currency':_0x2b8693,'unit_amount':_0x38037f,'product':_0x28e4ba,'metadata':{'id':_0x54c188}}):stripe['prices']['create']({'currency':_0x2b8693,'unit_amount':_0x38037f,'product':_0x28e4ba,'metadata':{'id':_0x54c188},'recurring':{'interval':billingIntervalsToStripeBillingIntervals[_0x221fac]}});}__name(createStripeProductPricing,'createStripeProductPricing');async function deactivateStripeProductPricing(_0x9d88df){return stripe['prices']['update'](_0x9d88df,{'active':![]});}__name(deactivateStripeProductPricing,'deactivateStripeProductPricing');async function createStripeProduct(_0x3715df,_0x599914){const _0xe9c50f=await stripe['products']['create']({'name':_0x3715df,'metadata':{'paymentPlanId':_0x599914}});return _0xe9c50f;}__name(createStripeProduct,'createStripeProduct');async function deactivateStripeProduct(_0x2b7a24){const _0x16801d=await stripe['products']['list'](),_0x45d2d3=_0x16801d['data']['filter'](_0x37aed7=>{return _0x37aed7['name']===_0x2b7a24;});for(const _0x382a6a of _0x45d2d3){await stripe['products']['update'](_0x382a6a['id'],{'active':![]});}}__name(deactivateStripeProduct,'deactivateStripeProduct');async function getStripeProducts(){const _0x1b1a81=await stripe['products']['list']();return _0x1b1a81['data'];}__name(getStripeProducts,'getStripeProducts');async function getStripeProductIdByPriceId(_0x57b70d){const {product:_0xb4937f}=await stripe['prices']['retrieve'](_0x57b70d);return isString(_0xb4937f)?_0xb4937f:_0xb4937f['id'];}__name(getStripeProductIdByPriceId,'getStripeProductIdByPriceId');async function setCustomerDefaultPaymentMethod(_0xa62964,_0x4a6e2d){await stripe['customers']['update'](_0x4a6e2d,{'invoice_settings':{'default_payment_method':_0xa62964}});}__name(setCustomerDefaultPaymentMethod,'setCustomerDefaultPaymentMethod');async function changeCustomerEmail(_0x20dd77,_0x288716){await stripe['customers']['update'](_0x20dd77,{'email':_0x288716});}__name(changeCustomerEmail,'changeCustomerEmail');async function getStripeDefaultPaymentMethod(_0x5d00ba){const _0x4980e6=await findStripeCustomerById(_0x5d00ba);if(_0x4980e6['deleted']||!_0x4980e6['invoice_settings']['default_payment_method'])return void(0x1*-0x8cb+0x20c5+-0x17fa);const _0xe6ec8e=isString(_0x4980e6['invoice_settings']['default_payment_method'])?_0x4980e6['invoice_settings']['default_payment_method']:_0x4980e6['invoice_settings']['default_payment_method']['id'],_0x2e63fb=await stripe['paymentMethods']['retrieve'](_0xe6ec8e);return _0x2e63fb;}__name(getStripeDefaultPaymentMethod,'getStripeDefaultPaymentMethod');async function detachAllPaymentMethodsFromCustomer(_0x48a812){const _0x3eee77=await stripe['customers']['listPaymentMethods'](_0x48a812),_0xfc09fc=_0x3eee77['data']['map'](_0x30d831=>_0x30d831['id']);await Promise['all'](_0xfc09fc['map'](detachPaymentMethod));}__name(detachAllPaymentMethodsFromCustomer,'detachAllPaymentMethodsFromCustomer');

export { areEnvSettingsConfiguredForPaymentSystem, attachPaymentMethodToCustomer, cancelStripeSubscription, cancelStripeSubscriptionById, changeCustomerEmail, changeStripeProductName, changeStripeProductStatus, confirmStripePayment, createStripeCustomer, createStripeProduct, createStripeProductPricing, createStripeSubscription, createStripeTrialSubscription, deactivateStripeProduct, deactivateStripeProductPricing, findStripeCustomerByEmail, findStripeCustomerById, getStripeDefaultPaymentMethod, getStripePaymentData, getStripeProductIdByPriceId, getStripeProducts, getStripeSubscriptionData, getStripeSubscriptionStatus, getSubscriptionFromPaymentIntent, hasStripeSubscription, instantUpdateStripeSubscription, processPaymentFailureAndCancelSubscription, retrievePaymentIntentFromSubscription, setCustomerDefaultPaymentMethod, stripe, updateCustomerEmailIfNeeded, updateStripeSubscriptionWithoutProration };
