'use strict';
import { areEnvSettingsConfiguredForPaymentSystem, getStripeDefaultPaymentMethod, findStripeCustomerByEmail, createStripeCustomer, createStripeSubscription, createStripeTrialSubscription, retrievePaymentIntentFromSubscription, confirmStripePayment, hasStripeSubscription, getStripeSubscriptionData, getSubscriptionFromPaymentIntent, getStripePaymentData, cancelStripeSubscriptionById, changeStripeProductName, deactivateStripeProduct, changeStripeProductStatus, getStripeProductIdByPriceId, stripe, setCustomerDefaultPaymentMethod, attachPaymentMethodToCustomer, updateCustomerEmailIfNeeded } from '../stripe/stripes.js';
import { crudCreate } from '../../../meta/server/basic-crud/cruds.js';
import { getResource } from '../../../meta/server/db/db.js';
import { resourceNames } from '../../../../fd-toolbox/resources/resource-names.js';
import { unixTimestampToDate, getNow } from '../../../../fd-toolbox/time/date-time.js';
import { hasPaidOrTrialSubscription, getActiveSubscriptionByWorkspaceId, changeSubscriptionStatus } from '../subscriptions/subscriptions.js';
import { getUserId } from '../../../meta/server/auth/users/current-user-id-provider.js';
import { getCurrentWorkspaceId } from '../../../meta/server/providers/current-workspace-id-provider.js';
import { apiNotFoundResponse, apiNoContentResponse, apiOkResponse, apiCreatedResponse } from '../../../meta/server/web/responses.js';
import { apiInternalServerError, apiBadRequestError, apiNotFoundError, apiConflictError } from '../../../../fd-toolbox/server/web/errors.js';
import { paymentErrorMessages, paymentErrors } from '../../../common/payments/payment-constants.js';
import { subscriptionStatuses } from '../../../meta/core/resources/enums/payment-enums.js';
import { Payment } from '../../../common/payments/payment.resource.js';
import { paymentStatus } from '../../../common/payments/stripe/stripe-constants.js';
import { Subscription } from '../../../meta/subscription-plan/subscription.resource.js';
import { getObjectValues } from '../../../../fd-toolbox/lib/utils.js';
import { updateWorkspacePricingId, setWorkspacePaymentSystemId, getCurrentWorkspace } from '../../../fd-app-toolbox/server/infra/workspaces/workspace-db.js';
import { isProdOrDemo } from '../../../../fd-toolbox/lib/environments.js';
import { getPaymentPlanByPricingId } from './payment-plan-db.js';
import { isPaymentPlanTrial } from './payment-plans.js';
import { toolboxUserConstants } from '../../../meta/constants/toolbox-users.js';
import { currencyCodes } from '../../../../fd-toolbox/constants/currency-constants.js';

var __defProp=Object['defineProperty'],__name=(_0x11da1b,_0x41a918)=>__defProp(_0x11da1b,'name',{'value':_0x41a918,'configurable':!![]});async function registerPaymentCustomerAndCreateWorkspaceSubscription(_0x30167b,_0x473bb6,_0x4f2d08,_0x56001a){let _0x5c93e6;_0x5c93e6=await getCurrentPaymentSystemCustomerId(),_0x5c93e6??=await createPaymentSystemCustomer(_0x30167b,_0x473bb6),await attachPaymentSystemPaymentMethodToPaymentSystemCustomer(_0x5c93e6,_0x56001a),await setPaymentMethodAsDefault(_0x56001a,_0x5c93e6);const _0x283740=await getPaymentPlanByPricingId(_0x4f2d08);if(!_0x283740)throw apiInternalServerError(paymentErrorMessages['noPaymentPlanAttachedToPricing']);if(!isPaymentPlanTrial(_0x283740))return createSubscriptionWithInstantPayment(_0x4f2d08,_0x56001a,_0x5c93e6);else {if(await hasPaidOrTrialSubscription())throw apiBadRequestError(paymentErrorMessages['trialCannotBeCreated']);return createTrialSubscription(_0x4f2d08,_0x56001a,_0x5c93e6);}}__name(registerPaymentCustomerAndCreateWorkspaceSubscription,'registerPaymentCustomerAndCreateWorkspaceSubscription');async function changeCurrentUserDefaultPaymentMethod(_0x474259){if(!areEnvSettingsConfiguredForPaymentSystem())return apiNotFoundResponse(paymentErrorMessages['environmentSettingsForPaymentSystemAreNotConfigured']);const _0x1ec1be=await getCurrentPaymentSystemCustomerId();if(!_0x1ec1be)throw apiNotFoundError(paymentErrorMessages['paymentSystemUserNotFound']);return await attachPaymentSystemPaymentMethodToPaymentSystemCustomer(_0x1ec1be,_0x474259),await setPaymentMethodAsDefault(_0x474259,_0x1ec1be),apiNoContentResponse();}__name(changeCurrentUserDefaultPaymentMethod,'changeCurrentUserDefaultPaymentMethod');async function getCurrentDefaultPaymentMethod(){if(!areEnvSettingsConfiguredForPaymentSystem())return apiNotFoundResponse(paymentErrorMessages['environmentSettingsForPaymentSystemAreNotConfigured']);const _0x5cef99=await getCurrentPaymentSystemCustomerId();if(!_0x5cef99)throw apiNotFoundError(paymentErrorMessages['paymentSystemUserNotFound']);const _0x3fc901=await getStripeDefaultPaymentMethod(_0x5cef99);if(!_0x3fc901)throw apiNotFoundError(paymentErrorMessages['defaultPaymentMethodNotFound']);if(!_0x3fc901['card'])throw apiNotFoundError(paymentErrorMessages['cardAttachedToPaymentMethodNotFound']);const _0xacbce9={'brand':_0x3fc901['card']['brand'],'safeCardNumber':_0x3fc901['card']['last4'],'expMonth':_0x3fc901['card']['exp_month'],'expYear':_0x3fc901['card']['exp_year']};return apiOkResponse(_0xacbce9);}__name(getCurrentDefaultPaymentMethod,'getCurrentDefaultPaymentMethod');async function createTrialSubscription(_0x3e6a61,_0x11258f,_0x19a023){const _0x4b8fba=await getCurrentWorkspaceId(),_0x44d4cb=await subscribeTrial(_0x3e6a61,_0x11258f,_0x19a023),_0x366005=await getActiveSubscriptionByWorkspaceId(_0x4b8fba);return _0x366005&&await changeSubscriptionStatus(_0x366005['id'],subscriptionStatuses['paused']),await updateWorkspacePricingId(_0x4b8fba,_0x3e6a61),await storeTrialSubscription(_0x44d4cb,_0x3e6a61),apiCreatedResponse({'isPaymentCompleted':!![]});}__name(createTrialSubscription,'createTrialSubscription');async function createSubscriptionWithInstantPayment(_0x1b7cd7,_0x2ea83c,_0x10c26b){const _0x40e237=await getCurrentWorkspaceId(),{transactionId:_0x3b92c0,confirmedPaymentStatus:_0x50e680,clientSecret:_0x331bdc,subscriptionId:_0x518697}=await subscribeAndPay(_0x1b7cd7,_0x2ea83c,_0x10c26b);if(_0x50e680===paymentStatus['requiresAction']&&_0x331bdc)return apiOkResponse({'isPaymentCompleted':![],'clientSecret':_0x331bdc,'subscriptionId':_0x518697});const _0xbf35e2=await getSubscriptionFromTransactionId(_0x3b92c0),_0x54189f=await getActiveSubscriptionByWorkspaceId(_0x40e237);return _0x54189f&&await changeSubscriptionStatus(_0x54189f['id'],subscriptionStatuses['paused']),await updateWorkspacePricingId(_0x40e237,_0x1b7cd7),await storePaymentData(_0x3b92c0,_0xbf35e2,_0x1b7cd7),apiCreatedResponse({'isPaymentCompleted':!![]});}__name(createSubscriptionWithInstantPayment,'createSubscriptionWithInstantPayment');async function subscribeAndPay(_0x5d8d13,_0x233201,_0x3153f5){const {paymentSystemPriceId:_0x3b56a8}=await getResource({'resourceName':resourceNames['pricing'],'id':_0x5d8d13},!![]);if(!_0x3b56a8)throw apiBadRequestError(paymentErrors['paymentFailed']);const _0x172034=await hasPaymentSystemSubscription(_0x3153f5,_0x3b56a8);if(_0x172034)throw apiConflictError(paymentErrors['alreadyPaid']);const _0x295eaf=await createPaymentSystemSubscription(_0x3153f5,_0x3b56a8,_0x233201),_0x1c42a4=await getInvoiceToPaySubscription(_0x295eaf),{transactionId:_0x14c095,confirmedPaymentStatus:_0x2481e9,clientSecret:_0x4bc002}=await completePayment(_0x1c42a4,_0x233201,_0x295eaf);return {'transactionId':_0x14c095,'confirmedPaymentStatus':_0x2481e9,'clientSecret':_0x4bc002,'subscriptionId':_0x295eaf};}__name(subscribeAndPay,'subscribeAndPay');async function subscribeTrial(_0x1f66e6,_0x577eea,_0x3293a0){const {paymentSystemPriceId:_0x39b35c}=await getResource({'resourceName':resourceNames['pricing'],'id':_0x1f66e6});if(!_0x39b35c)throw apiBadRequestError(paymentErrors['paymentFailed']);const _0x2f39a8=await hasPaymentSystemSubscription(_0x3293a0,_0x39b35c);if(_0x2f39a8)throw apiConflictError(paymentErrors['alreadyPaid']);const _0x1aed12=await createPaymentSystemTrialSubscription(_0x3293a0,_0x39b35c,_0x577eea);return _0x1aed12;}__name(subscribeTrial,'subscribeTrial');async function createPaymentSystemCustomer(_0xc972ce,_0x70420c){const _0x480b25=await getCurrentWorkspaceId();if(isProdOrDemo()){const _0xb800a2=await findStripeCustomerByEmail(_0x70420c);if(_0xb800a2)throw apiConflictError(paymentErrors['emailAlreadyUsed']['replace']('{0}',_0x70420c));}const _0x28bd0a=await createStripeCustomer(_0xc972ce,_0x70420c,_0x480b25);if(!_0x28bd0a?.['id'])throw apiBadRequestError(paymentErrors['paymentFailed']);return await setWorkspacePaymentSystemId(_0x28bd0a['id']),_0x28bd0a['id'];}__name(createPaymentSystemCustomer,'createPaymentSystemCustomer');async function createPaymentSystemSubscription(_0x1bfa13,_0x269797,_0x3e41c5){const _0x20abcb=await createStripeSubscription(_0x1bfa13,_0x269797,_0x3e41c5);if(!_0x20abcb?.['id'])throw apiBadRequestError(paymentErrors['paymentFailed']);return _0x20abcb['id'];}__name(createPaymentSystemSubscription,'createPaymentSystemSubscription');async function createPaymentSystemTrialSubscription(_0x34a4bc,_0x556d9b,_0x59080e){const _0x97829d=await createStripeTrialSubscription(_0x34a4bc,_0x556d9b,_0x59080e);if(!_0x97829d?.['id'])throw apiBadRequestError(paymentErrors['paymentFailed']);return _0x97829d['id'];}__name(createPaymentSystemTrialSubscription,'createPaymentSystemTrialSubscription');async function getInvoiceToPaySubscription(_0x53dca5){const _0x3cf2ce=await retrievePaymentIntentFromSubscription(_0x53dca5);if(!_0x3cf2ce?.['id'])throw apiBadRequestError(paymentErrors['paymentFailed']);const _0x3ecd02=_0x3cf2ce['id'];return _0x3ecd02;}__name(getInvoiceToPaySubscription,'getInvoiceToPaySubscription');async function completePayment(_0x3c51d0,_0x5a3390,_0x4903c3){const _0x411f41=await confirmStripePayment(_0x3c51d0,_0x5a3390,_0x4903c3);return {'transactionId':_0x411f41['id'],'confirmedPaymentStatus':_0x411f41['status'],'clientSecret':_0x411f41['client_secret']};}__name(completePayment,'completePayment');async function hasPaymentSystemSubscription(_0x4dc274,_0x27d88f){return hasStripeSubscription(_0x4dc274,_0x27d88f);}__name(hasPaymentSystemSubscription,'hasPaymentSystemSubscription');async function getSubscriptionPeriodEndDate(_0x2be400){const {currentPeriodEndDate:_0x24a7d0}=await getStripeSubscriptionData(_0x2be400);return unixTimestampToDate(_0x24a7d0);}__name(getSubscriptionPeriodEndDate,'getSubscriptionPeriodEndDate');async function getSubscriptionTrialEndDate(_0x3b8120){const {trialEnd:_0xe2fedc}=await getStripeSubscriptionData(_0x3b8120);if(!_0xe2fedc)throw apiConflictError(paymentErrorMessages['trialSubscriptionDataNotFound']);return unixTimestampToDate(_0xe2fedc);}__name(getSubscriptionTrialEndDate,'getSubscriptionTrialEndDate');async function getSubscriptionFromTransactionId(_0x5e494c){const _0x294ab4=await getSubscriptionFromPaymentIntent(_0x5e494c);return _0x294ab4;}__name(getSubscriptionFromTransactionId,'getSubscriptionFromTransactionId');async function storePaymentData(_0x220a85,_0x5d44f0,_0x380c0f){const _0x11aee6=new Subscription();_0x11aee6['pricingId']=_0x380c0f,_0x11aee6['status']=subscriptionStatuses['active'],_0x11aee6['paymentSystemSubscriptionId']=_0x5d44f0,_0x11aee6['currentPeriodStartDate']=getNow(),_0x11aee6['currentPeriodEndDate']=await getSubscriptionPeriodEndDate(_0x5d44f0);const _0x4d8fad=await crudCreate({'userId':toolboxUserConstants['workerBotId'],'resourceName':resourceNames['subscription'],'resource':_0x11aee6,'throwOnNonSuccess':!![]}),{amount:_0x18d360,currency:_0x4985e9,paymentMethodId:_0x54f6d9}=await getAfterPaymentDetails(_0x220a85),_0x27000e=new Payment();_0x27000e['amount']=_0x18d360,_0x27000e['currency']=_0x4985e9,_0x27000e['paymentMethodId']=_0x54f6d9,_0x27000e['subscriptionId']=_0x4d8fad['result']['id'],_0x27000e['paymentTransactionId']=_0x220a85,await crudCreate({'userId':toolboxUserConstants['workerBotId'],'resourceName':resourceNames['payment'],'resource':_0x27000e,'throwOnNonSuccess':!![]});}__name(storePaymentData,'storePaymentData');async function storeTrialSubscription(_0xbb8d37,_0x21955a){const _0x58f3d9=new Subscription();_0x58f3d9['pricingId']=_0x21955a,_0x58f3d9['status']=subscriptionStatuses['trialing'],_0x58f3d9['paymentSystemSubscriptionId']=_0xbb8d37,_0x58f3d9['currentPeriodStartDate']=getNow(),_0x58f3d9['currentPeriodEndDate']=await getSubscriptionTrialEndDate(_0xbb8d37),await crudCreate({'userId':await getUserId(),'resourceName':resourceNames['subscription'],'resource':_0x58f3d9,'throwOnNonSuccess':!![]});}__name(storeTrialSubscription,'storeTrialSubscription');async function getAfterPaymentDetails(_0x1bfc3f){const {amount:_0x53f35b,currency:_0x4d1367,paymentMethodId:_0x4bf46c,status:_0x535165}=await getStripePaymentData(_0x1bfc3f);if(_0x535165!==paymentStatus['succeeded'])throw apiBadRequestError(paymentErrors['paymentFailed']);const _0x5f414b=getObjectValues(currencyCodes)['find'](_0x258a88=>_0x258a88===_0x4d1367['toUpperCase']());if(!_0x5f414b)throw apiBadRequestError(paymentErrors['paymentFailed']);if(!_0x4bf46c||typeof _0x4bf46c!=='string')throw apiBadRequestError(paymentErrors['paymentFailed']);return {'paymentMethodId':_0x4bf46c,'amount':_0x53f35b,'currency':_0x5f414b};}__name(getAfterPaymentDetails,'getAfterPaymentDetails');async function cancelIncompleteSubscription(_0x51ebfa){await cancelStripeSubscriptionById(_0x51ebfa);}__name(cancelIncompleteSubscription,'cancelIncompleteSubscription');async function changePaymentSystemPlanName(_0x3a5645,_0xdbb7d){return changeStripeProductName(_0x3a5645,_0xdbb7d);}__name(changePaymentSystemPlanName,'changePaymentSystemPlanName');async function deactivatePaymentPlan(_0x2f9823){return deactivateStripeProduct(_0x2f9823);}__name(deactivatePaymentPlan,'deactivatePaymentPlan');async function changePaymentSystemPlanStatus(_0x54b867,_0x60d10b){return changeStripeProductStatus(_0x54b867,_0x60d10b);}__name(changePaymentSystemPlanStatus,'changePaymentSystemPlanStatus');async function getPaymentPlanIdByPriceId(_0x59ad46){return getStripeProductIdByPriceId(_0x59ad46);}__name(getPaymentPlanIdByPriceId,'getPaymentPlanIdByPriceId');async function getCurrentPaymentSystemCustomerId(){const _0x160df2=await getCurrentWorkspace();return _0x160df2['paymentSystemCustomerId'];}__name(getCurrentPaymentSystemCustomerId,'getCurrentPaymentSystemCustomerId');function detachPaymentMethod(_0x489268){return stripe['paymentMethods']['detach'](_0x489268);}__name(detachPaymentMethod,'detachPaymentMethod');async function setPaymentMethodAsDefault(_0x13494e,_0x2b5625){await setCustomerDefaultPaymentMethod(_0x13494e,_0x2b5625);}__name(setPaymentMethodAsDefault,'setPaymentMethodAsDefault');async function attachPaymentSystemPaymentMethodToPaymentSystemCustomer(_0x477618,_0x76fd84){await attachPaymentMethodToCustomer(_0x477618,_0x76fd84),await updateCustomerEmailIfNeeded(_0x477618,_0x76fd84);}__name(attachPaymentSystemPaymentMethodToPaymentSystemCustomer,'attachPaymentSystemPaymentMethodToPaymentSystemCustomer');

export { cancelIncompleteSubscription, changeCurrentUserDefaultPaymentMethod, changePaymentSystemPlanName, changePaymentSystemPlanStatus, completePayment, createPaymentSystemCustomer, createPaymentSystemSubscription, createPaymentSystemTrialSubscription, createSubscriptionWithInstantPayment, createTrialSubscription, deactivatePaymentPlan, detachPaymentMethod, getAfterPaymentDetails, getCurrentDefaultPaymentMethod, getCurrentPaymentSystemCustomerId, getInvoiceToPaySubscription, getPaymentPlanIdByPriceId, getSubscriptionFromTransactionId, getSubscriptionPeriodEndDate, getSubscriptionTrialEndDate, hasPaymentSystemSubscription, registerPaymentCustomerAndCreateWorkspaceSubscription, storePaymentData, storeTrialSubscription, subscribeAndPay, subscribeTrial };
