'use strict';
import { apiForbiddenError, apiBadRequestError, apiInternalServerError, apiNotFoundError } from '../../../../fd-toolbox/server/web/errors.js';
import { updateStripeSubscriptionWithoutProration, cancelStripeSubscription, getStripeSubscriptionData, getStripeDefaultPaymentMethod, instantUpdateStripeSubscription } from '../stripe/stripes.js';
import { getSubscriptionsByWorkspaceId, changeSubscriptionStatusById, getSubscriptionsDueForCheck, getFreeSubscriptionByWorkspaceId } from './subscription-db.js';
import { unixTimestampToDate } from '../../../../fd-toolbox/time/date-time.js';
import { mapSubscriptionStatusToDbFormat } from '../../utils/map-subscription-status-to-db-format.js';
import { subscriptionStatuses } from '../../../meta/core/resources/enums/payment-enums.js';
import { getResource, getResourcesByName } from '../../../meta/server/db/db.js';
import { resourceNames } from '../../../../fd-toolbox/resources/resource-names.js';
import { crudUpdate } from '../../../meta/server/basic-crud/cruds.js';
import { getUserId } from '../../../meta/server/auth/users/current-user-id-provider.js';
import { paymentErrorMessages, pricingIds } from '../../../common/payments/payment-constants.js';
import { getCurrentPaymentSystemCustomerId, createSubscriptionWithInstantPayment } from '../payments/payments.js';
import { getPaymentPlanByPricingId } from '../payments/payment-plan-db.js';
import { isPaymentPlanTrial } from '../payments/payment-plans.js';
import { ensureNotNullOrUndefined } from '../../../../fd-toolbox/functions/value-checking-functions.js';

var __defProp=Object['defineProperty'],__name=(_0xbb70e1,_0xc37d21)=>__defProp(_0xbb70e1,'name',{'value':_0xc37d21,'configurable':!![]});async function cancelPaidSubscription(_0x315257,_0x4e3376){const _0x44d2fa=await getSubscriptionsByWorkspaceId(_0x4e3376),_0x51b90e=_0x44d2fa['some'](_0x5ed358=>_0x5ed358['id']===_0x315257);if(!_0x51b90e)throw apiForbiddenError();const _0x2e3b73=_0x44d2fa['find'](_0x278df5=>_0x278df5['id']===_0x315257);if(!_0x2e3b73?.['paymentSystemSubscriptionId'])throw apiBadRequestError();if(_0x2e3b73['pendingPricingId']){const _0x265d14=await updateSubscriptionById(_0x315257,{'pendingPricingId':void(0x13*-0x1eb+-0x8*-0x3c3+-0x5*-0x145),'endDate':_0x2e3b73['currentPeriodEndDate']}),_0x535ce0=await getResource({'resourceName':resourceNames['pricing'],'id':_0x2e3b73['pricingId']});return updateStripeSubscriptionWithoutProration(_0x2e3b73['paymentSystemSubscriptionId'],_0x535ce0['paymentSystemPriceId']),_0x265d14;}const _0x4dadd8=await cancelStripeSubscription(_0x2e3b73['paymentSystemSubscriptionId']),_0x4b5b58={'status':mapSubscriptionStatusToDbFormat(_0x4dadd8['subscriptionStatus']),'currentPeriodEndDate':unixTimestampToDate(_0x4dadd8?.['currentPeriodEndDate']),'endDate':_0x4dadd8?.['endDate']?unixTimestampToDate(_0x4dadd8['endDate']):void(0x1804+-0x1039*0x1+0x7*-0x11d),'pendingPricingId':void(-0x276*-0x2+-0x1970+0x1a*0xca)};return updateSubscriptionById(_0x315257,_0x4b5b58);}__name(cancelPaidSubscription,'cancelPaidSubscription');async function updatePaymentPlan(_0x587c73,_0x15798b){const _0x296abe=await getResource({'resourceName':resourceNames['subscription'],'id':_0x587c73}),_0x4e90b5=await getResource({'resourceName':resourceNames['pricing'],'id':_0x15798b}),_0x78807e=_0x296abe['paymentSystemSubscriptionId'],_0x37808a=_0x4e90b5['paymentSystemPriceId'];if(_0x296abe['status']===subscriptionStatuses['trialing'])throw apiForbiddenError(paymentErrorMessages['subscriptionCannotBeUpdatedDueToTrial']);const _0x86e307=await getPaymentPlanByPricingId(_0x15798b);if(!_0x86e307)throw apiInternalServerError(paymentErrorMessages['noPaymentPlanAttachedToPricing']);if(isPaymentPlanTrial(_0x86e307))throw apiBadRequestError(paymentErrorMessages['subscriptionCannotBeUpgradedToTrial']);const _0xa160e8=await getResource({'resourceName':resourceNames['pricing'],'id':_0x15798b}),_0x4d7fd3=await getResource({'resourceName':resourceNames['pricing'],'id':_0x296abe['pricingId']});_0xa160e8['price']>=_0x4d7fd3['price']?await upgradePaymentPlan(_0x587c73,_0x78807e,_0x37808a,_0x15798b):await downgradePaymentPlan(_0x587c73,_0x78807e,_0x37808a,_0x15798b);}__name(updatePaymentPlan,'updatePaymentPlan');async function changeSubscriptionStatus(_0x419c2f,_0x36b38b){return changeSubscriptionStatusById(_0x419c2f,_0x36b38b);}__name(changeSubscriptionStatus,'changeSubscriptionStatus');async function getActiveSubscriptionByWorkspaceId(_0x3841c3){const _0x1c5e74=await getSubscriptionsByWorkspaceId(_0x3841c3),_0x4d1586=_0x1c5e74['find'](_0x3bf1c3=>_0x3bf1c3['status']===subscriptionStatuses['active']||_0x3bf1c3['status']===subscriptionStatuses['trialing']);return _0x4d1586;}__name(getActiveSubscriptionByWorkspaceId,'getActiveSubscriptionByWorkspaceId');async function syncInactiveSubscriptions(){const _0x51f9dd=await getSubscriptionsDueForCheck();if(!_0x51f9dd['length'])return;for(const _0x13ee5d of _0x51f9dd){if(_0x13ee5d?.['paymentSystemSubscriptionId']){const _0x538fca=await getFreeSubscriptionByWorkspaceId(_0x13ee5d['workspaceId']),_0xc25863=await getStripeSubscriptionData(_0x13ee5d['paymentSystemSubscriptionId']),_0x293345=mapSubscriptionStatusToDbFormat(_0xc25863['status']);_0x293345!==_0x13ee5d['status']&&_0x293345!==subscriptionStatuses['active']&&_0x293345!==subscriptionStatuses['pastDue']&&await processInactiveSubscriptionSync(_0x13ee5d['id'],ensureNotNullOrUndefined(_0x538fca)['id'],_0xc25863);}}}__name(syncInactiveSubscriptions,'syncInactiveSubscriptions');async function processInactiveSubscriptionSync(_0x512bb1,_0x1f027e,_0x55815e){const _0x44339b={'status':subscriptionStatuses['canceled'],'currentPeriodEndDate':unixTimestampToDate(_0x55815e['currentPeriodEndDate']),'endDate':_0x55815e['endDate']?unixTimestampToDate(_0x55815e['endDate']):void(0x11e9+0xfc3+0x35e*-0xa)};await updateSubscriptionById(_0x512bb1,_0x44339b),await changeSubscriptionStatusById(_0x1f027e,subscriptionStatuses['active']);}__name(processInactiveSubscriptionSync,'processInactiveSubscriptionSync');async function hasPaidOrTrialSubscription(){const _0x4ac7b5=await getResourcesByName(resourceNames['subscription']);return _0x4ac7b5['some'](_0x129298=>_0x129298['pricingId']!==pricingIds['basicId']);}__name(hasPaidOrTrialSubscription,'hasPaidOrTrialSubscription');async function createSubscriptionForCurrentWorkspace(_0x27809d){const _0x115cfc=await getCurrentPaymentSystemCustomerId();if(!_0x115cfc)throw apiNotFoundError(paymentErrorMessages['paymentSystemUserNotFound']);const _0x125549=await getStripeDefaultPaymentMethod(_0x115cfc),_0x5396c8=_0x125549?.['id'];if(!_0x5396c8)throw apiNotFoundError(paymentErrorMessages['defaultPaymentMethodNotFound']);const _0x17e344=await getPaymentPlanByPricingId(_0x27809d);if(!_0x17e344)throw apiInternalServerError(paymentErrorMessages['noPaymentPlanAttachedToPricing']);if(isPaymentPlanTrial(_0x17e344))throw apiBadRequestError(paymentErrorMessages['trialCannotBeCreated']);return createSubscriptionWithInstantPayment(_0x27809d,_0x5396c8,_0x115cfc);}__name(createSubscriptionForCurrentWorkspace,'createSubscriptionForCurrentWorkspace');async function downgradePaymentPlan(_0x4d89da,_0x8be315,_0x5de61a,_0x218d5b){await updateStripeSubscriptionWithoutProration(_0x8be315,_0x5de61a);const _0x1de321={'pendingPricingId':_0x218d5b,'endDate':void(0x22a+-0xc0e+-0xd3*-0xc)};return updateSubscriptionById(_0x4d89da,_0x1de321);}__name(downgradePaymentPlan,'downgradePaymentPlan');async function upgradePaymentPlan(_0xaee3f7,_0x49adaa,_0x2f1680,_0x5efc00){await instantUpdateStripeSubscription(_0x49adaa,_0x2f1680);const _0x481087={'pricingId':_0x5efc00,'endDate':void(-0x30*-0xc7+0x185*0x7+-0x2ff3),'pendingPricingId':void(0x4b7+-0x12a6+-0x29*-0x57)};return updateSubscriptionById(_0xaee3f7,_0x481087);}__name(upgradePaymentPlan,'upgradePaymentPlan');async function updateSubscriptionById(_0x5a8e2c,_0x2ad55b){const _0x5a7ec1=await getUserId(),_0x30ebd6={'id':_0x5a8e2c,..._0x2ad55b},_0xf0fd94={'resourceName':resourceNames['subscription'],'resource':_0x30ebd6,'isCreate':![],'throwOnNonSuccess':!![],'userId':_0x5a7ec1};await crudUpdate(_0xf0fd94);}__name(updateSubscriptionById,'updateSubscriptionById');

export { cancelPaidSubscription, changeSubscriptionStatus, createSubscriptionForCurrentWorkspace, getActiveSubscriptionByWorkspaceId, hasPaidOrTrialSubscription, processInactiveSubscriptionSync, syncInactiveSubscriptions, updatePaymentPlan };
