Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
55.4 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import type {UserID} from '@app/api/BrandedTypes';
import type {GiftCodeDurationType} from '@app/api/database/types/PaymentTypes';
import type {UserRow} from '@app/api/database/types/UserTypes';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import {Logger} from '@app/api/Logger';
import {getWorkerService} from '@app/api/middleware/ServiceRegistry';
import {getPaymentDisputeRepository} from '@app/api/middleware/ServiceSingletons';
import {addGiftCodeDuration} from '@app/api/models/GiftCode';
import type {User} from '@app/api/models/User';
import {assertNoOpenPaymentDispute} from '@app/api/payment_disputes/PaymentDisputeReviews';
import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';
import type {DistributionPriceSync} from '@app/api/stripe/DistributionPriceSync';
import {
	findChannelPrice,
	resolveDistributionRule,
	resolveListPriceId,
	subscriptionDistributionMetadata,
} from '@app/api/stripe/DistributionPricing';
import type {ProductInfo, RecurringBillingCycle} from '@app/api/stripe/ProductRegistry';
import {
	buildGiftTrialMetadata,
	getGiftTrialPaidUntil,
	isGiftTrialRunning,
	isPastStripeTrialLimit,
} from '@app/api/stripe/StripeGiftTrialMetadata';
import {mirrorSubscription} from '@app/api/stripe/StripeMirror';
import {
	getPrimarySubscriptionItem,
	getSubscriptionEntitlementPeriodEndUnix,
	getSubscriptionItemPeriodEndUnix,
	getSubscriptionPremiumPeriodEnd,
	loadSubscriptionSchedule,
} from '@app/api/stripe/StripeSubscriptionPeriod';
import {extractId} from '@app/api/stripe/StripeUtils';
import {type BillingCancelSource, enqueueBillingEmail} from '@app/api/stripe/services/BillingEmailService';
import {CLEARED_CANCEL_METADATA, subscriptionCancelling} from '@app/api/stripe/services/BillingSubscriptionDetails';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {dispatchUserUpdate} from '@app/api/user/UserMappers';
import type {Currency} from '@app/api/utils/CurrencyUtils';
import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
import {NoActiveSubscriptionError} from '@fluxer/errors/src/domains/payment/NoActiveSubscriptionError';
import {StripeBillingCycleChangeNeedsResubscribeError} from '@fluxer/errors/src/domains/payment/StripeBillingCycleChangeNeedsResubscribeError';
import {StripeError} from '@fluxer/errors/src/domains/payment/StripeError';
import {StripeInvalidProductConfigurationError} from '@fluxer/errors/src/domains/payment/StripeInvalidProductConfigurationError';
import {StripeNoActiveSubscriptionError} from '@fluxer/errors/src/domains/payment/StripeNoActiveSubscriptionError';
import {StripeNoSubscriptionError} from '@fluxer/errors/src/domains/payment/StripeNoSubscriptionError';
import {StripePaymentNotAvailableError} from '@fluxer/errors/src/domains/payment/StripePaymentNotAvailableError';
import {StripeSubscriptionAlreadyCancelingError} from '@fluxer/errors/src/domains/payment/StripeSubscriptionAlreadyCancelingError';
import {StripeSubscriptionNotCancelingError} from '@fluxer/errors/src/domains/payment/StripeSubscriptionNotCancelingError';
import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
	CurrentSubscriptionPriceResponse,
	SwitchToListPriceResponse,
} from '@fluxer/schema/src/domains/premium/PremiumSchemas';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
import {seconds} from 'itty-time';
import type Stripe from 'stripe';

type BillingCycleChangeEffectiveAt = 'now' | 'period_end';

const CHARGEABLE_SUBSCRIPTION_STATUSES = new Set<Stripe.Subscription.Status>(['active', 'trialing']);

function mapStripeIds(values: Array<string | {id: string}> | null | undefined): Array<string> | null {
	const ids = (values ?? []).map((value) => extractId(value)).filter((id): id is string => id !== null);
	return ids.length > 0 ? ids : null;
}

function mapSchedulePhaseDiscounts(
	discounts:
		| Array<{
				coupon: string | {id: string} | null;
				discount: unknown;
				promotion_code: string | {id: string} | null;
		  }>
		| null
		| undefined,
): Array<Stripe.SubscriptionScheduleUpdateParams.Phase.Discount> | null {
	const mapped = (discounts ?? [])
		.map((discount): Stripe.SubscriptionScheduleUpdateParams.Phase.Discount | null => {
			const coupon = extractId(discount.coupon);
			if (coupon) {
				return {coupon};
			}
			const promotionCode = extractId(discount.promotion_code);
			if (promotionCode) {
				return {promotion_code: promotionCode};
			}
			return typeof discount.discount === 'string' ? {discount: discount.discount} : null;
		})
		.filter((discount): discount is Stripe.SubscriptionScheduleUpdateParams.Phase.Discount => discount !== null);
	return mapped.length > 0 ? mapped : null;
}

function mapSchedulePhaseAddInvoiceItems(
	addInvoiceItems: Array<Stripe.SubscriptionSchedule.Phase.AddInvoiceItem> | null | undefined,
): Array<Stripe.SubscriptionScheduleUpdateParams.Phase.AddInvoiceItem> | null {
	const mapped = (addInvoiceItems ?? [])
		.map((addInvoiceItem) => {
			const price = extractId(addInvoiceItem.price);
			if (!price) {
				return null;
			}
			const mappedItem: Stripe.SubscriptionScheduleUpdateParams.Phase.AddInvoiceItem = {
				price,
				quantity: addInvoiceItem.quantity ?? 1,
				period: addInvoiceItem.period,
			};
			const taxRates = mapStripeIds(addInvoiceItem.tax_rates);
			if (taxRates) {
				mappedItem.tax_rates = taxRates;
			}
			const discounts = mapSchedulePhaseDiscounts(addInvoiceItem.discounts);
			if (discounts) {
				mappedItem.discounts = discounts;
			}
			if (addInvoiceItem.metadata) {
				mappedItem.metadata = addInvoiceItem.metadata;
			}
			return mappedItem;
		})
		.filter(
			(addInvoiceItem): addInvoiceItem is Stripe.SubscriptionScheduleUpdateParams.Phase.AddInvoiceItem =>
				addInvoiceItem !== null,
		);
	return mapped.length > 0 ? mapped : null;
}

export type GiftTrialExtension =
	| {kind: 'extended'; subscription: Stripe.Subscription}
	| {kind: 'already_applied'}
	| {kind: 'past_trial_limit'};

export class StripeSubscriptionService {
	constructor(
		private stripe: Stripe | null,
		private userRepository: UserRepository,
		private productRegistry: {
			getRecurringSubscriptionPriceId: (billingCycle: RecurringBillingCycle, currency: string) => string | null;
			getProduct: (priceId: string) => ProductInfo | null;
		},
		private cacheService: ICacheService,
		private gatewayService: IGatewayService,
		private storeEntitlementService: StoreEntitlementService | null = null,
		private distributionPriceSync: DistributionPriceSync | null = null,
	) {}

	private distributionMetadataForPriceChange(
		currentPriceId: string,
		targetPriceId: string,
	): Record<string, string> | null {
		return findChannelPrice(currentPriceId) || findChannelPrice(targetPriceId)
			? subscriptionDistributionMetadata(targetPriceId)
			: null;
	}

	private async resolveCycleChangeTargetPriceId(currentPriceId: string, baseTargetPriceId: string): Promise<string> {
		const current = findChannelPrice(currentPriceId);
		if (!current || !this.distributionPriceSync) {
			return baseTargetPriceId;
		}
		const rule = resolveDistributionRule(current.id, 'plutonium_subscription');
		if (!rule) {
			return baseTargetPriceId;
		}
		return (await this.distributionPriceSync.ensureChannelPrice(rule, baseTargetPriceId)).price_id;
	}

	async cancelSubscriptionAtPeriodEnd(userId: UserID, source: BillingCancelSource): Promise<void> {
		if (!this.stripe) {
			throw new StripePaymentNotAvailableError();
		}
		const user = await this.userRepository.findUnique(userId);
		if (!user) {
			throw new UnknownUserError();
		}
		if (!user.stripeSubscriptionId) {
			throw new StripeNoActiveSubscriptionError();
		}
		if (user.premiumWillCancel) {
			throw new StripeSubscriptionAlreadyCancelingError();
		}
		const requestedAt = Math.floor(Date.now() / 1000);
		const metadata = {fluxer_cancel_source: source, fluxer_cancel_requested_at: String(requestedAt)};
		try {
			const subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId, {
				expand: ['items.data.price', 'schedule'],
			});
			const schedule = await loadSubscriptionSchedule(this.stripe, subscription.schedule);
			if (schedule) {
				await this.stripe.subscriptions.update(user.stripeSubscriptionId, {metadata});
				try {
					await this.cancelScheduledSubscriptionAtPeriodEnd(user, subscription, schedule);
				} catch (error) {
					await this.clearCancelSource(subscription.id);
					throw error;
				}
				await this.confirmCancellation(subscription.id, source, requestedAt);
				return;
			}
			const updatedSubscription = await this.stripe.subscriptions.update(user.stripeSubscriptionId, {
				cancel_at_period_end: true,
				metadata,
			});
			await mirrorSubscription(
				updatedSubscription,
				user.id,
				'Mirror upsert failed after Stripe write; reconciler will heal',
			);
			const updatedUser = await this.userRepository.patchUpsert(
				userId,
				{
					premium_will_cancel: true,
				},
				user.toRow(),
			);
			await dispatchUserUpdate(this.gatewayService, updatedUser);
			await this.confirmCancellation(updatedSubscription.id, source, requestedAt);
			Logger.debug({userId, subscriptionId: user.stripeSubscriptionId}, 'Subscription set to cancel at period end');
		} catch (error: unknown) {
			Logger.error(
				{error, userId, subscriptionId: user.stripeSubscriptionId},
				'Failed to cancel subscription at period end',
			);
			const message = error instanceof Error ? error.message : 'Failed to cancel subscription';
			throw new StripeError(message);
		}
	}

	private async confirmCancellation(
		subscriptionId: string,
		source: BillingCancelSource,
		requestedAt: number,
	): Promise<void> {
		if (source !== 'customer_request') {
			return;
		}
		try {
			await enqueueBillingEmail(getWorkerService(), {
				kind: 'subscription_cancel_scheduled',
				id: subscriptionId,
				requestedAt,
			});
		} catch (error) {
			Logger.error({error, subscriptionId}, 'Cancelled a subscription but could not queue the confirmation email');
		}
	}

	async cancelSubscriptionImmediately(userId: UserID, reason?: string, expectedSubscriptionId?: string): Promise<void> {
		if (!this.stripe) {
			throw new StripePaymentNotAvailableError();
		}
		const user = await this.userRepository.findUnique(userId);
		if (!user) {
			throw new UnknownUserError();
		}
		if (!user.stripeSubscriptionId) {
			throw new StripeNoActiveSubscriptionError();
		}
		if (expectedSubscriptionId && user.stripeSubscriptionId !== expectedSubscriptionId) {
			Logger.info(
				{
					userId: user.id.toString(),
					expectedSubscriptionId,
					currentSubscriptionId: user.stripeSubscriptionId,
					reason: reason ?? null,
				},
				'Skipping immediate cancellation because the target subscription is no longer the current one',
			);
			return;
		}
		try {
			const canceledSubscription = await this.stripe.subscriptions.cancel(
				user.stripeSubscriptionId,
				{
					invoice_now: false,
					prorate: false,
					...(reason
						? {
								cancellation_details: {
									comment: reason,
								},
							}
						: {}),
				},
				{idempotencyKey: `admin-cancel-now:${user.id}:${user.stripeSubscriptionId}`},
			);
			await mirrorSubscription(
				canceledSubscription,
				user.id,
				'Mirror upsert failed after Stripe write; reconciler will heal',
			);
			const patch: Partial<UserRow> = {
				premium_will_cancel: false,
				premium_billing_cycle: null,
				stripe_subscription_id: null,
				premium_grace_ends_at: null,
			};
			if (user.premiumType !== UserPremiumTypes.LIFETIME) {
				const now = new Date();
				const paidUntil = getGiftTrialPaidUntil(canceledSubscription, now.getTime()) ?? user.premiumUntil;
				const giftEnd = this.pullGiftExtensionBackToNow(user.premiumGiftExtensionEndsAt, paidUntil, now);
				const hasActiveGift = giftEnd != null && giftEnd.getTime() > now.getTime();
				Object.assign(patch, {
					premium_type: hasActiveGift ? user.premiumType : UserPremiumTypes.NONE,
					premium_since: hasActiveGift ? user.premiumSince : null,
					premium_until: now,
					premium_gift_extension_ends_at: giftEnd,
				});
			}
			const updatedUser = await this.userRepository.patchUpsert(userId, patch, user.toRow());
			await dispatchUserUpdate(this.gatewayService, updatedUser);
			Logger.debug({userId, subscriptionId: user.stripeSubscriptionId}, 'Subscription canceled immediately');
		} catch (error: unknown) {
			Logger.error(
				{error, userId, subscriptionId: user.stripeSubscriptionId},
				'Failed to cancel subscription immediately',
			);
			const message = error instanceof Error ? error.message : 'Failed to cancel subscription immediately';
			throw new StripeError(message);
		}
		await this.storeEntitlementService?.reapplyAfterStripeChange(userId);
	}

	private async clearCancelSource(subscriptionId: string): Promise<void> {
		try {
			await this.stripe?.subscriptions.update(subscriptionId, {metadata: CLEARED_CANCEL_METADATA});
		} catch (error) {
			Logger.error({error, subscriptionId}, 'Could not clear the cancellation source after a failed cancellation');
		}
	}

	private async confirmGiftApplied(subscription: Stripe.Subscription, trialEnd: number): Promise<void> {
		if (subscriptionCancelling(subscription, null)) {
			return;
		}
		try {
			await enqueueBillingEmail(getWorkerService(), {kind: 'gift_applied', id: subscription.id, trialEnd});
		} catch (error) {
			Logger.error(
				{error, subscriptionId: subscription.id},
				'Applied a gift but could not queue the confirmation email',
			);
		}
	}

	private pullGiftExtensionBackToNow(giftEnd: Date | null, paidUntil: Date | null, now: Date): Date | null {
		if (!giftEnd || !paidUntil || paidUntil.getTime() <= now.getTime() || giftEnd.getTime() < paidUntil.getTime()) {
			return giftEnd;
		}
		return new Date(giftEnd.getTime() - (paidUntil.getTime() - now.getTime()));
	}

	async reactivateSubscription(userId: UserID): Promise<void> {
		if (!this.stripe) {
			throw new StripePaymentNotAvailableError();
		}
		const user = await this.userRepository.findUnique(userId);
		if (!user) {
			throw new UnknownUserError();
		}
		if (!user.stripeSubscriptionId) {
			throw new StripeNoSubscriptionError();
		}
		if (!user.premiumWillCancel) {
			throw new StripeSubscriptionNotCancelingError();
		}
		await assertNoOpenPaymentDispute(getPaymentDisputeRepository(), user.id);
		try {
			let subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId, {
				expand: ['schedule'],
			});
			const schedule = await loadSubscriptionSchedule(this.stripe, subscription.schedule);
			if (schedule) {
				await this.stripe.subscriptionSchedules.release(schedule.id, {
					preserve_cancel_date: false,
				});
				subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId, {
					expand: ['items.data.price'],
				});
			}
			const clearCancellationParams = this.getClearCancellationUpdateParams(subscription);
			const hasCancelSource = Boolean(
				subscription.metadata?.fluxer_cancel_source || subscription.metadata?.fluxer_cancel_requested_at,
			);
			const reactivatedSubscription =
				clearCancellationParams || hasCancelSource
					? await this.stripe.subscriptions.update(user.stripeSubscriptionId, {
							...clearCancellationParams,
							metadata: CLEARED_CANCEL_METADATA,
						})
					: subscription;
			await mirrorSubscription(
				reactivatedSubscription,
				user.id,
				'Mirror upsert failed after Stripe write; reconciler will heal',
			);
			const updatedUser = await this.userRepository.patchUpsert(
				userId,
				{
					premium_will_cancel: false,
				},
				user.toRow(),
			);
			await dispatchUserUpdate(this.gatewayService, updatedUser);
			Logger.debug({userId, subscriptionId: user.stripeSubscriptionId}, 'Subscription reactivated');
		} catch (error: unknown) {
			Logger.error({error, userId, subscriptionId: user.stripeSubscriptionId}, 'Failed to reactivate subscription');
			const message = error instanceof Error ? error.message : 'Failed to reactivate subscription';
			throw new StripeError(message);
		}
	}

	async cancelPendingSubscriptionChange(userId: UserID): Promise<void> {
		if (!this.stripe) {
			throw new StripePaymentNotAvailableError();
		}
		const user = await this.userRepository.findUnique(userId);
		if (!user) {
			throw new UnknownUserError();
		}
		if (!user.stripeSubscriptionId) {
			throw new StripeNoActiveSubscriptionError();
		}
		try {
			const subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId, {
				expand: ['items.data.price', 'schedule'],
			});
			const schedule = await loadSubscriptionSchedule(this.stripe, subscription.schedule);
			if (!schedule || !this.subscriptionScheduleHasPendingBillingCycleChange(schedule, subscription)) {
				Logger.debug(
					{userId, subscriptionId: user.stripeSubscriptionId, scheduleId: schedule?.id ?? null},
					'No pending subscription billing-cycle change to cancel',
				);
				return;
			}
			await this.stripe.subscriptionSchedules.release(schedule.id, {
				preserve_cancel_date: Boolean(subscription.cancel_at || subscription.cancel_at_period_end),
			});
			const releasedSubscription = await this.stripe.subscriptions.retrieve(subscription.id, {
				expand: ['items.data.price'],
			});
			await mirrorSubscription(
				releasedSubscription,
				user.id,
				'Mirror upsert failed after releasing pending billing-cycle schedule; reconciler will heal',
			);
			const patch: Record<string, unknown> = {
				premium_will_cancel: Boolean(releasedSubscription.cancel_at || releasedSubscription.cancel_at_period_end),
			};
			const computedPremiumUntil = getSubscriptionPremiumPeriodEnd(releasedSubscription);
			if (computedPremiumUntil) {
				patch['premium_until'] = computedPremiumUntil;
			}
			const updatedCustomerId = extractId(releasedSubscription.customer);
			if (updatedCustomerId && updatedCustomerId !== user.stripeCustomerId) {
				patch['stripe_customer_id'] = updatedCustomerId;
			}
			const updatedUser = await this.userRepository.patchUpsert(userId, patch, user.toRow());
			await dispatchUserUpdate(this.gatewayService, updatedUser);
			Logger.debug(
				{userId, subscriptionId: user.stripeSubscriptionId, scheduleId: schedule.id},
				'Pending subscription billing-cycle change canceled',
			);
		} catch (error: unknown) {
			Logger.error(
				{error, userId, subscriptionId: user.stripeSubscriptionId},
				'Failed to cancel pending subscription billing-cycle change',
			);
			const message =
				error instanceof Error ? error.message : 'Failed to cancel pending subscription billing-cycle change';
			throw new StripeError(message);
		}
	}

	async changeBillingCycle(
		userId: UserID,
		billingCycle: RecurringBillingCycle,
		effectiveAt: BillingCycleChangeEffectiveAt = 'now',
	): Promise<void> {
		if (!this.stripe) {
			throw new StripePaymentNotAvailableError();
		}
		const user = await this.userRepository.findUnique(userId);
		if (!user) {
			throw new UnknownUserError();
		}
		if (!user.stripeSubscriptionId) {
			throw new StripeNoActiveSubscriptionError();
		}
		await assertNoOpenPaymentDispute(getPaymentDisputeRepository(), user.id);
		try {
			const subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId, {
				expand: ['schedule', 'default_payment_method'],
			});
			const item = getPrimarySubscriptionItem(subscription);
			if (!item?.id || !item.price?.recurring || !item.price.currency) {
				throw new StripeError('Subscription is missing a recurring primary item');
			}
			if (isMandatePaidSubscription(subscription)) {
				throw new StripeBillingCycleChangeNeedsResubscribeError();
			}
			const currentBillingCycle = this.getBillingCycleFromInterval(item.price.recurring.interval);
			if (!currentBillingCycle) {
				throw new StripeError('Unsupported recurring interval for subscription');
			}
			if (currentBillingCycle === billingCycle) {
				Logger.debug(
					{userId, subscriptionId: user.stripeSubscriptionId, billingCycle},
					'Skipping billing cycle change because the target cycle is already active',
				);
				return;
			}
			const baseTargetPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, item.price.currency);
			if (!baseTargetPriceId) {
				throw new StripeInvalidProductConfigurationError();
			}
			const targetPriceId = await this.resolveCycleChangeTargetPriceId(item.price.id, baseTargetPriceId);
			const scheduledChange = await loadSubscriptionSchedule(this.stripe, subscription.schedule);
			if (scheduledChange && this.subscriptionScheduleHasFutureTargetPrice(scheduledChange, targetPriceId)) {
				const patch: Record<string, unknown> = {
					premium_will_cancel: false,
				};
				const computedPremiumUntil = getSubscriptionPremiumPeriodEnd(subscription);
				if (computedPremiumUntil) {
					patch['premium_until'] = computedPremiumUntil;
				}
				const updatedCustomerId = extractId(subscription.customer);
				if (updatedCustomerId && updatedCustomerId !== user.stripeCustomerId) {
					patch['stripe_customer_id'] = updatedCustomerId;
				}
				const updatedUser = await this.userRepository.patchUpsert(userId, patch, user.toRow());
				await dispatchUserUpdate(this.gatewayService, updatedUser);
				Logger.debug(
					{
						userId,
						subscriptionId: user.stripeSubscriptionId,
						scheduleId: scheduledChange.id,
						toBillingCycle: billingCycle,
						targetPriceId,
					},
					'Skipping immediate billing cycle change because the target cycle is already scheduled',
				);
				return;
			}
			if (effectiveAt === 'period_end' || currentBillingCycle === 'yearly') {
				await this.scheduleBillingCycleChangeAtPeriodEnd({
					user,
					subscription,
					item,
					currentBillingCycle,
					targetBillingCycle: billingCycle,
					targetPriceId,
				});
				return;
			}
			const clearCancellationParams = this.getClearCancellationUpdateParams(subscription) ?? {};
			const distributionMetadata = this.distributionMetadataForPriceChange(item.price.id, targetPriceId);
			const distributionMetadataPatch = distributionMetadata ? {metadata: distributionMetadata} : {};
			const updatedSubscription = await this.stripe.subscriptions.update(user.stripeSubscriptionId, {
				...clearCancellationParams,
				...distributionMetadataPatch,
				items: [
					{
						id: item.id,
						price: targetPriceId,
						quantity: item.quantity ?? 1,
					},
				],
				payment_behavior: 'error_if_incomplete',
				proration_behavior: 'always_invoice',
			});
			await mirrorSubscription(
				updatedSubscription,
				user.id,
				'Mirror upsert failed after Stripe write; reconciler will heal',
			);
			const patch: Record<string, unknown> = {
				premium_billing_cycle: billingCycle,
				premium_will_cancel: false,
			};
			const computedPremiumUntil = getSubscriptionPremiumPeriodEnd(updatedSubscription);
			if (computedPremiumUntil) {
				patch['premium_until'] = computedPremiumUntil;
			}
			const updatedCustomerId = extractId(updatedSubscription.customer);
			if (updatedCustomerId && updatedCustomerId !== user.stripeCustomerId) {
				patch['stripe_customer_id'] = updatedCustomerId;
			}
			const updatedUser = await this.userRepository.patchUpsert(userId, patch, user.toRow());
			await dispatchUserUpdate(this.gatewayService, updatedUser);
			Logger.debug(
				{
					userId,
					subscriptionId: user.stripeSubscriptionId,
					fromBillingCycle: currentBillingCycle,
					toBillingCycle: billingCycle,
					targetPriceId,
					premiumUntil: computedPremiumUntil,
				},
				'Subscription billing cycle changed',
			);
		} catch (error: unknown) {
			Logger.error(
				{error, userId, subscriptionId: user.stripeSubscriptionId, billingCycle, effectiveAt},
				'Failed to change subscription billing cycle',
			);
			if (
				error instanceof StripeError ||
				error instanceof StripeInvalidProductConfigurationError ||
				error instanceof StripeBillingCycleChangeNeedsResubscribeError
			) {
				throw error;
			}
			const message = error instanceof Error ? error.message : 'Failed to change subscription billing cycle';
			throw new StripeError(message);
		}
	}

	async switchToCurrentListPrice(userId: UserID): Promise<SwitchToListPriceResponse> {
		if (!this.stripe) {
			throw new StripePaymentNotAvailableError();
		}
		const user = await this.userRepository.findUnique(userId);
		if (!user) {
			throw new UnknownUserError();
		}
		if (!user.stripeSubscriptionId) {
			throw new StripeNoActiveSubscriptionError();
		}
		await assertNoOpenPaymentDispute(getPaymentDisputeRepository(), user.id);
		const lockKey = `list_price_switch_lock:${user.id}`;
		const lockToken = await this.cacheService.acquireLock(
			lockKey,
			StripeSubscriptionService.LIST_PRICE_SWITCH_LOCK_TTL_SECONDS,
		);
		if (!lockToken) {
			Logger.debug(
				{userId, subscriptionId: user.stripeSubscriptionId, lockKey},
				'List price switch skipped because another switch is already in flight',
			);
			return {status: 'ineligible', reason: 'switch_in_progress'};
		}
		try {
			const subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId, {
				expand: ['items.data.price', 'schedule'],
			});
			const item = getPrimarySubscriptionItem(subscription);
			if (!item?.id || !item.price?.recurring || !item.price.currency || item.price.unit_amount == null) {
				return {status: 'ineligible', reason: 'unsupported_subscription'};
			}
			if (!CHARGEABLE_SUBSCRIPTION_STATUSES.has(subscription.status)) {
				return {status: 'ineligible', reason: 'subscription_not_chargeable'};
			}
			if (subscription.cancel_at != null || subscription.cancel_at_period_end) {
				return {status: 'ineligible', reason: 'subscription_cancelling'};
			}
			const billingCycle = this.getBillingCycleFromInterval(item.price.recurring.interval);
			if (!billingCycle) {
				return {status: 'ineligible', reason: 'unsupported_subscription'};
			}
			const currency = item.price.currency.toUpperCase() as Currency;
			const baseListPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);
			const targetPriceId = resolveListPriceId(item.price.id, baseListPriceId);
			if (!targetPriceId) {
				return {status: 'ineligible', reason: 'no_list_price'};
			}
			if (targetPriceId === item.price.id) {
				return {status: 'ineligible', reason: 'already_on_list_price'};
			}
			const targetProduct = this.productRegistry.getProduct(targetPriceId);
			if (!targetProduct || targetProduct.currency !== currency) {
				return {status: 'ineligible', reason: 'no_list_price'};
			}
			const targetAmountMinor = await this.getListPriceAmountMinor(targetPriceId);
			const currentAmountMinor = item.price.unit_amount;
			if (targetAmountMinor == null) {
				return {status: 'ineligible', reason: 'no_list_price'};
			}
			if (targetAmountMinor >= currentAmountMinor) {
				return {status: 'ineligible', reason: 'not_a_price_decrease'};
			}
			const periodEnd = getSubscriptionEntitlementPeriodEndUnix(subscription, item);
			if (!periodEnd || periodEnd <= Math.floor(Date.now() / 1000)) {
				return {status: 'ineligible', reason: 'missing_period_end'};
			}
			const switched = {
				effective_at: new Date(periodEnd * 1000).toISOString(),
				target_price_id: targetPriceId,
				target_amount_minor: targetAmountMinor,
				current_amount_minor: currentAmountMinor,
				currency,
			};
			const schedule = await loadSubscriptionSchedule(this.stripe, subscription.schedule);
			const pendingSchedule =
				schedule && (schedule.status === 'active' || schedule.status === 'not_started') ? schedule : null;
			if (pendingSchedule) {
				if (this.subscriptionScheduleHasFutureTargetPrice(pendingSchedule, targetPriceId)) {
					Logger.debug(
						{userId, subscriptionId: subscription.id, scheduleId: pendingSchedule.id, targetPriceId},
						'List price switch already scheduled for period end',
					);
					return {status: 'already_scheduled', ...switched};
				}
				if (pendingSchedule.end_behavior === 'cancel') {
					return {status: 'ineligible', reason: 'cancellation_managed_by_schedule'};
				}
				if (this.subscriptionScheduleHasPendingBillingCycleChange(pendingSchedule, subscription)) {
					return {status: 'ineligible', reason: 'conflicting_pending_change'};
				}
			}
			await this.scheduleBillingCycleChangeAtPeriodEnd({
				user,
				subscription,
				item,
				currentBillingCycle: billingCycle,
				targetBillingCycle: billingCycle,
				targetPriceId,
				clearCancellation: false,
			});
			Logger.debug(
				{
					userId,
					subscriptionId: subscription.id,
					billingCycle,
					currency,
					currentPriceId: item.price.id,
					targetPriceId,
					currentAmountMinor,
					targetAmountMinor,
					periodEnd,
				},
				'Subscription switch to current list price scheduled for period end',
			);
			return {status: 'scheduled', ...switched};
		} catch (error: unknown) {
			Logger.error(
				{error, userId, subscriptionId: user.stripeSubscriptionId},
				'Failed to switch subscription to the current list price',
			);
			if (error instanceof StripeError || error instanceof StripeInvalidProductConfigurationError) {
				throw error;
			}
			const message = error instanceof Error ? error.message : 'Failed to switch subscription to the list price';
			throw new StripeError(message);
		} finally {
			try {
				const released = await this.cacheService.releaseLock(lockKey, lockToken);
				if (!released) {
					Logger.warn({userId, lockKey}, 'List price switch lock token no longer matched on release');
				}
			} catch (error) {
				Logger.error({error, userId, lockKey}, 'Failed to release list price switch lock');
			}
		}
	}

	private async scheduleBillingCycleChangeAtPeriodEnd({
		user,
		subscription,
		item,
		currentBillingCycle,
		targetBillingCycle,
		targetPriceId,
		clearCancellation = true,
	}: {
		user: User;
		subscription: Stripe.Subscription;
		item: Stripe.SubscriptionItem;
		currentBillingCycle: RecurringBillingCycle;
		targetBillingCycle: RecurringBillingCycle;
		targetPriceId: string;
		clearCancellation?: boolean;
	}): Promise<void> {
		if (!this.stripe) {
			throw new StripePaymentNotAvailableError();
		}
		const periodEnd = getSubscriptionEntitlementPeriodEndUnix(subscription, item);
		if (!periodEnd || periodEnd <= Math.floor(Date.now() / 1000)) {
			throw new StripeError('Subscription is missing a future period end for scheduled billing cycle change');
		}
		let currentSubscription = subscription;
		if (clearCancellation && (subscription.cancel_at || subscription.cancel_at_period_end)) {
			currentSubscription = await this.stripe.subscriptions.update(
				subscription.id,
				this.getClearCancellationUpdateParams(subscription) ?? {proration_behavior: 'none'},
			);
			await mirrorSubscription(
				currentSubscription,
				user.id,
				'Mirror upsert failed after clearing cancellation for scheduled billing cycle change; reconciler will heal',
			);
		}
		const scheduleId = extractId(currentSubscription.schedule);
		const schedule = scheduleId
			? await this.stripe.subscriptionSchedules.retrieve(scheduleId)
			: await this.stripe.subscriptionSchedules.create({
					from_subscription: currentSubscription.id,
				});
		const currentPhase = this.buildCurrentSchedulePhase(schedule, currentSubscription, item, periodEnd);
		const firstInvoiceCredit = await this.buildPeriodEndCycleSwapCredit({
			subscription: currentSubscription,
			item,
			currentBillingCycle,
			targetBillingCycle,
			targetPriceId,
		});
		const firstInvoiceCreditAmountMinor =
			firstInvoiceCredit?.price_data?.unit_amount != null ? -firstInvoiceCredit.price_data.unit_amount : null;
		const targetPhase: Stripe.SubscriptionScheduleUpdateParams.Phase = {
			start_date: periodEnd,
			items: [
				{
					price: targetPriceId,
					quantity: item.quantity ?? 1,
				},
			],
			proration_behavior: 'none',
		};
		if (currentBillingCycle !== targetBillingCycle) {
			targetPhase.billing_cycle_anchor = 'phase_start';
		}
		if (firstInvoiceCredit) {
			targetPhase.add_invoice_items = [firstInvoiceCredit];
			targetPhase.metadata = {
				first_invoice_credit_amount_minor: String(firstInvoiceCreditAmountMinor),
				first_invoice_credit_source: 'current_period_payment',
			};
		}
		const distributionMetadata = this.distributionMetadataForPriceChange(item.price.id, targetPriceId);
		if (distributionMetadata) {
			targetPhase.metadata = {...targetPhase.metadata, ...distributionMetadata};
		}
		await this.stripe.subscriptionSchedules.update(schedule.id, {
			end_behavior: clearCancellation ? 'release' : schedule.end_behavior,
			proration_behavior: 'none',
			metadata: {
				user_id: user.id.toString(),
				pending_billing_cycle: targetBillingCycle,
			},
			phases: [currentPhase, targetPhase],
		});
		let scheduledSubscription = currentSubscription;
		if (!clearCancellation) {
			scheduledSubscription = await this.stripe.subscriptions.retrieve(currentSubscription.id, {
				expand: ['items.data.price'],
			});
			await mirrorSubscription(
				scheduledSubscription,
				user.id,
				'Mirror upsert failed after scheduling a period-end price change; reconciler will heal',
			);
		}
		const patch: Record<string, unknown> = {
			premium_will_cancel: clearCancellation
				? false
				: Boolean(scheduledSubscription.cancel_at || scheduledSubscription.cancel_at_period_end),
		};
		const computedPremiumUntil = getSubscriptionPremiumPeriodEnd(scheduledSubscription);
		if (computedPremiumUntil) {
			patch['premium_until'] = computedPremiumUntil;
		}
		const updatedCustomerId = extractId(scheduledSubscription.customer);
		if (updatedCustomerId && updatedCustomerId !== user.stripeCustomerId) {
			patch['stripe_customer_id'] = updatedCustomerId;
		}
		const updatedUser = await this.userRepository.patchUpsert(user.id, patch, user.toRow());
		await dispatchUserUpdate(this.gatewayService, updatedUser);
		Logger.debug(
			{
				userId: user.id,
				subscriptionId: scheduledSubscription.id,
				scheduleId: schedule.id,
				fromBillingCycle: currentBillingCycle,
				toBillingCycle: targetBillingCycle,
				targetPriceId,
				firstInvoiceCreditAmountMinor,
				periodEnd,
			},
			'Subscription billing cycle change scheduled for period end',
		);
	}

	private async cancelScheduledSubscriptionAtPeriodEnd(
		user: User,
		subscription: Stripe.Subscription,
		schedule: Stripe.SubscriptionSchedule,
	): Promise<void> {
		if (!this.stripe) {
			throw new StripePaymentNotAvailableError();
		}
		const item = getPrimarySubscriptionItem(subscription);
		const periodEnd = getSubscriptionEntitlementPeriodEndUnix(subscription, item);
		if (!item || !periodEnd || periodEnd <= Math.floor(Date.now() / 1000)) {
			throw new StripeError('Subscription is missing a future period end for scheduled cancellation');
		}
		const currentPhase = this.buildCurrentSchedulePhase(schedule, subscription, item, periodEnd);
		await this.stripe.subscriptionSchedules.update(schedule.id, {
			end_behavior: 'cancel',
			proration_behavior: 'none',
			metadata: {
				...schedule.metadata,
				user_id: user.id.toString(),
				pending_billing_cycle: '',
				cancellation_source: 'self_serve',
			},
			phases: [currentPhase],
		});
		const updatedSubscription = await this.stripe.subscriptions.retrieve(subscription.id, {
			expand: ['items.data.price'],
		});
		await mirrorSubscription(
			updatedSubscription,
			user.id,
			'Mirror upsert failed after schedule-managed cancellation; reconciler will heal',
		);
		const patch: Record<string, unknown> = {
			premium_will_cancel: true,
		};
		const computedPremiumUntil = getSubscriptionPremiumPeriodEnd(updatedSubscription);
		if (computedPremiumUntil) {
			patch['premium_until'] = computedPremiumUntil;
		}
		const updatedCustomerId = extractId(updatedSubscription.customer);
		if (updatedCustomerId && updatedCustomerId !== user.stripeCustomerId) {
			patch['stripe_customer_id'] = updatedCustomerId;
		}
		const updatedUser = await this.userRepository.patchUpsert(user.id, patch, user.toRow());
		await dispatchUserUpdate(this.gatewayService, updatedUser);
		Logger.debug(
			{userId: user.id, subscriptionId: subscription.id, scheduleId: schedule.id, periodEnd},
			'Subscription schedule set to cancel at period end',
		);
	}

	private async buildPeriodEndCycleSwapCredit({
		subscription,
		item,
		currentBillingCycle,
		targetBillingCycle,
		targetPriceId,
	}: {
		subscription: Stripe.Subscription;
		item: Stripe.SubscriptionItem;
		currentBillingCycle: RecurringBillingCycle;
		targetBillingCycle: RecurringBillingCycle;
		targetPriceId: string;
	}): Promise<Stripe.SubscriptionScheduleUpdateParams.Phase.AddInvoiceItem | null> {
		if (!this.stripe || currentBillingCycle !== 'monthly' || targetBillingCycle !== 'yearly') {
			return null;
		}
		if (subscription.trial_end != null && subscription.trial_end > Math.floor(Date.now() / 1000)) {
			return null;
		}
		const currentAmountMinor = item.price.unit_amount;
		if (currentAmountMinor == null || currentAmountMinor <= 0) {
			return null;
		}
		const targetPrice = await this.stripe.prices.retrieve(targetPriceId);
		const targetAmountMinor = targetPrice.unit_amount;
		const targetProductId = extractId(targetPrice.product);
		if (!targetProductId || targetAmountMinor == null || targetAmountMinor <= 0) {
			return null;
		}
		const quantity = item.quantity ?? 1;
		const creditAmountMinor = Math.min(currentAmountMinor * quantity, targetAmountMinor * quantity);
		if (creditAmountMinor <= 0) {
			return null;
		}
		const creditInvoiceItem: Stripe.SubscriptionScheduleUpdateParams.Phase.AddInvoiceItem & {discountable: boolean} = {
			discountable: false,
			price_data: {
				currency: targetPrice.currency,
				product: targetProductId,
				tax_behavior: 'unspecified',
				unit_amount: -creditAmountMinor,
			},
			quantity: 1,
			metadata: {
				reason: 'period_end_cycle_swap_credit',
				credited_price_id: item.price.id,
				credited_amount_minor: String(creditAmountMinor),
			},
		};
		return creditInvoiceItem;
	}

	private getClearCancellationUpdateParams(subscription: Stripe.Subscription): Stripe.SubscriptionUpdateParams | null {
		if (subscription.cancel_at_period_end) {
			return {
				cancel_at_period_end: false,
				proration_behavior: 'none',
				metadata: CLEARED_CANCEL_METADATA,
			};
		}
		if (subscription.cancel_at != null) {
			return {
				cancel_at: null,
				proration_behavior: 'none',
				metadata: CLEARED_CANCEL_METADATA,
			};
		}
		return null;
	}

	private subscriptionScheduleHasFutureTargetPrice(
		schedule: Stripe.SubscriptionSchedule,
		targetPriceId: string,
	): boolean {
		const now = Math.floor(Date.now() / 1000);
		return schedule.phases.some(
			(phase) =>
				typeof phase.start_date === 'number' &&
				phase.start_date > now &&
				phase.items.some((phaseItem) => extractId(phaseItem.price) === targetPriceId),
		);
	}

	private subscriptionScheduleHasPendingBillingCycleChange(
		schedule: Stripe.SubscriptionSchedule,
		subscription: Stripe.Subscription,
	): boolean {
		const now = Math.floor(Date.now() / 1000);
		const currentItem = getPrimarySubscriptionItem(subscription);
		const currentPriceId = extractId(currentItem?.price);
		const currentBillingCycle = this.getBillingCycleFromInterval(currentItem?.price?.recurring?.interval ?? '');
		const metadataTargetBillingCycle =
			schedule.metadata?.pending_billing_cycle === 'monthly' || schedule.metadata?.pending_billing_cycle === 'yearly'
				? schedule.metadata.pending_billing_cycle
				: null;
		if (metadataTargetBillingCycle && metadataTargetBillingCycle !== currentBillingCycle) {
			return true;
		}
		return schedule.phases.some(
			(phase) =>
				typeof phase.start_date === 'number' &&
				phase.start_date > now &&
				phase.items.some((phaseItem) => {
					const phasePriceId = extractId(phaseItem.price);
					return phasePriceId != null && phasePriceId !== currentPriceId;
				}),
		);
	}

	private buildCurrentSchedulePhase(
		schedule: Stripe.SubscriptionSchedule,
		subscription: Stripe.Subscription,
		item: Stripe.SubscriptionItem,
		periodEnd: number,
	): Stripe.SubscriptionScheduleUpdateParams.Phase {
		const now = Math.floor(Date.now() / 1000);
		const phase =
			schedule.phases.find((candidate) => candidate.start_date <= now && candidate.end_date >= now) ??
			schedule.phases[0] ??
			null;
		const phaseItems =
			phase?.items
				.map((phaseItem) => {
					const price = extractId(phaseItem.price);
					if (!price) {
						return null;
					}
					const mappedItem: Stripe.SubscriptionScheduleUpdateParams.Phase.Item = {
						price,
						quantity: phaseItem.quantity ?? 1,
					};
					const itemTaxRates = mapStripeIds(phaseItem.tax_rates);
					if (itemTaxRates) {
						mappedItem.tax_rates = itemTaxRates;
					}
					const itemDiscounts = mapSchedulePhaseDiscounts(phaseItem.discounts);
					if (itemDiscounts) {
						mappedItem.discounts = itemDiscounts;
					}
					if (phaseItem.metadata) {
						mappedItem.metadata = phaseItem.metadata;
					}
					if (phaseItem.billing_thresholds?.usage_gte != null) {
						mappedItem.billing_thresholds = {usage_gte: phaseItem.billing_thresholds.usage_gte};
					}
					return mappedItem;
				})
				.filter((phaseItem): phaseItem is Stripe.SubscriptionScheduleUpdateParams.Phase.Item => phaseItem !== null) ??
			[];
		const currentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase = {
			start_date: phase?.start_date ?? subscription.start_date ?? subscription.created,
			end_date: periodEnd,
			items:
				phaseItems.length > 0
					? phaseItems
					: [
							{
								price: item.price.id,
								quantity: item.quantity ?? 1,
							},
						],
			proration_behavior: 'none',
		};
		if (phase) {
			const phaseDiscounts = mapSchedulePhaseDiscounts(phase.discounts);
			if (phaseDiscounts) {
				currentPhase.discounts = phaseDiscounts;
			}
			const defaultTaxRates = mapStripeIds(phase.default_tax_rates);
			if (defaultTaxRates) {
				currentPhase.default_tax_rates = defaultTaxRates;
			}
			if (phase.metadata) {
				currentPhase.metadata = phase.metadata;
			}
			if (phase.currency) {
				currentPhase.currency = phase.currency;
			}
			if (phase.description != null) {
				currentPhase.description = phase.description;
			}
			if (phase.collection_method) {
				currentPhase.collection_method = phase.collection_method;
			}
			if (phase.application_fee_percent != null) {
				currentPhase.application_fee_percent = phase.application_fee_percent;
			}
			const defaultPaymentMethod = extractId(phase.default_payment_method);
			if (defaultPaymentMethod) {
				currentPhase.default_payment_method = defaultPaymentMethod;
			}
			const onBehalfOf = extractId(phase.on_behalf_of);
			if (onBehalfOf) {
				currentPhase.on_behalf_of = onBehalfOf;
			}
			if (phase.automatic_tax) {
				const automaticTax: Stripe.SubscriptionScheduleUpdateParams.Phase.AutomaticTax = {
					enabled: phase.automatic_tax.enabled,
				};
				if (phase.automatic_tax.liability) {
					automaticTax.liability = {type: phase.automatic_tax.liability.type};
					const liabilityAccount = extractId(phase.automatic_tax.liability.account);
					if (liabilityAccount) {
						automaticTax.liability.account = liabilityAccount;
					}
				}
				currentPhase.automatic_tax = automaticTax;
			}
			if (phase.invoice_settings) {
				const invoiceSettings: Stripe.SubscriptionScheduleUpdateParams.Phase.InvoiceSettings = {};
				const accountTaxIds = mapStripeIds(phase.invoice_settings.account_tax_ids);
				if (accountTaxIds) {
					invoiceSettings.account_tax_ids = accountTaxIds;
				}
				if (phase.invoice_settings.days_until_due != null) {
					invoiceSettings.days_until_due = phase.invoice_settings.days_until_due;
				}
				if (phase.invoice_settings.issuer) {
					invoiceSettings.issuer = {type: phase.invoice_settings.issuer.type};
					const issuerAccount = extractId(phase.invoice_settings.issuer.account);
					if (issuerAccount) {
						invoiceSettings.issuer.account = issuerAccount;
					}
				}
				if (Object.keys(invoiceSettings).length > 0) {
					currentPhase.invoice_settings = invoiceSettings;
				}
			}
			if (phase.billing_thresholds) {
				const billingThresholds: Stripe.SubscriptionScheduleUpdateParams.Phase.BillingThresholds = {};
				if (phase.billing_thresholds.amount_gte != null) {
					billingThresholds.amount_gte = phase.billing_thresholds.amount_gte;
				}
				if (phase.billing_thresholds.reset_billing_cycle_anchor != null) {
					billingThresholds.reset_billing_cycle_anchor = phase.billing_thresholds.reset_billing_cycle_anchor;
				}
				if (Object.keys(billingThresholds).length > 0) {
					currentPhase.billing_thresholds = billingThresholds;
				}
			}
			if (phase.transfer_data) {
				const destination = extractId(phase.transfer_data.destination);
				if (destination) {
					currentPhase.transfer_data = {destination};
					if (phase.transfer_data.amount_percent != null) {
						currentPhase.transfer_data.amount_percent = phase.transfer_data.amount_percent;
					}
				}
			}
			if (phase.start_date > now) {
				const addInvoiceItems = mapSchedulePhaseAddInvoiceItems(phase.add_invoice_items);
				if (addInvoiceItems) {
					currentPhase.add_invoice_items = addInvoiceItems;
				}
			}
		}
		const trialEnd = subscription.trial_end;
		if (trialEnd != null && trialEnd > now) {
			if (trialEnd >= periodEnd) {
				currentPhase.trial = true;
			} else {
				currentPhase.trial_end = trialEnd;
			}
		}
		const phaseIsTrial = currentPhase.trial === true || currentPhase.trial_end != null;
		if (phase?.billing_cycle_anchor && !(phaseIsTrial && phase.billing_cycle_anchor === 'phase_start')) {
			currentPhase.billing_cycle_anchor = phase.billing_cycle_anchor;
		}
		return currentPhase;
	}

	async getCurrentSubscriptionPrice(userId: UserID): Promise<CurrentSubscriptionPriceResponse> {
		if (!this.stripe) {
			return null;
		}
		const user = await this.userRepository.findUnique(userId);
		if (!user) {
			throw new UnknownUserError();
		}
		if (!user.stripeSubscriptionId) {
			return null;
		}
		const cacheKey = `stripe:subscription:current_price:${user.stripeSubscriptionId}`;
		try {
			return await this.cacheService.getOrSet<CurrentSubscriptionPriceResponse>(
				cacheKey,
				async () => this.loadCurrentSubscriptionPrice(user.stripeSubscriptionId!),
				StripeSubscriptionService.CURRENT_PRICE_CACHE_TTL_SECONDS,
				StripeSubscriptionService.PRICE_CACHE_PRODUCE_TIMEOUT_MS,
			);
		} catch (error) {
			Logger.warn(
				{error, userId, subscriptionId: user.stripeSubscriptionId},
				'Failed to load current subscription price from Stripe',
			);
			return null;
		}
	}

	private async loadCurrentSubscriptionPrice(subscriptionId: string): Promise<CurrentSubscriptionPriceResponse> {
		if (!this.stripe) {
			return null;
		}
		const subscription = await this.stripe.subscriptions.retrieve(subscriptionId, {
			expand: ['items.data.price'],
		});
		const item = getPrimarySubscriptionItem(subscription);
		const price = item?.price;
		if (!price || price.unit_amount == null || !price.recurring || !price.currency) {
			return null;
		}
		const billingCycle = this.getBillingCycleFromInterval(price.recurring.interval);
		if (!billingCycle) {
			return null;
		}
		const currency = price.currency.toUpperCase() as Currency;
		const baseListPriceId = this.productRegistry.getRecurringSubscriptionPriceId(billingCycle, currency);
		const listPriceId = resolveListPriceId(price.id, baseListPriceId);
		const listAmountMinor = listPriceId ? await this.getListPriceAmountMinor(listPriceId) : null;
		const isGrandfathered = listPriceId != null && listPriceId !== price.id;
		return {
			price_id: price.id,
			amount_minor: price.unit_amount,
			currency,
			billing_cycle: billingCycle,
			is_grandfathered: isGrandfathered,
			list_price_id: listPriceId,
			list_amount_minor: listAmountMinor,
		};
	}

	private async getListPriceAmountMinor(priceId: string): Promise<number | null> {
		if (!this.stripe) {
			return null;
		}
		try {
			return await this.cacheService.getOrSet<number | null>(
				`stripe:list_price_amount:${priceId}`,
				async () => {
					const price = await this.stripe!.prices.retrieve(priceId);
					return price.unit_amount ?? null;
				},
				StripeSubscriptionService.LIST_PRICE_CACHE_TTL_SECONDS,
				StripeSubscriptionService.PRICE_CACHE_PRODUCE_TIMEOUT_MS,
			);
		} catch (error) {
			Logger.warn({error, priceId}, 'Failed to retrieve Stripe list price amount');
			return null;
		}
	}

	async extendSubscriptionWithGiftTrialDuration(
		user: User,
		durationType: GiftCodeDurationType,
		durationQuantity: number,
		idempotencyKey: string,
	): Promise<GiftTrialExtension> {
		if (!this.stripe || !user.stripeSubscriptionId) {
			Logger.debug(
				{
					userId: user.id,
					durationType,
					durationQuantity,
					idempotencyKey,
					hasStripeClient: Boolean(this.stripe),
					hasStripeSubscriptionId: Boolean(user.stripeSubscriptionId),
				},
				'Cannot extend subscription with gift trial duration: no active Stripe subscription context',
			);
			throw new NoActiveSubscriptionError();
		}
		const appliedKey = `gift_trial_applied:${user.id}:${idempotencyKey}`;
		const inflightKey = `gift_trial_inflight:${user.id}:${idempotencyKey}`;
		Logger.debug(
			{
				userId: user.id,
				subscriptionId: user.stripeSubscriptionId,
				durationType,
				durationQuantity,
				idempotencyKey,
				appliedKey,
				inflightKey,
			},
			'Starting Stripe gift trial extension',
		);
		if (await this.cacheService.get<boolean>(appliedKey)) {
			Logger.debug({userId: user.id, idempotencyKey}, 'Gift trial extension already applied (idempotent hit)');
			return {kind: 'already_applied'};
		}
		if (await this.cacheService.get<boolean>(inflightKey)) {
			Logger.debug({userId: user.id, idempotencyKey}, 'Gift trial extension in-flight; skipping duplicate');
			return {kind: 'already_applied'};
		}
		await this.cacheService.set(inflightKey, true, seconds('1 minute'));
		Logger.debug({userId: user.id, idempotencyKey, inflightKey}, 'Gift trial inflight sentinel set');
		const userLockKey = `gift_trial_user_lock:${user.id}`;
		const userLockToken = await this.acquireUserTrialLock(userLockKey, user.id);
		Logger.debug(
			{
				userId: user.id,
				idempotencyKey,
				userLockKey,
				lockAcquired: Boolean(userLockToken),
			},
			'Gift trial user lock acquisition completed',
		);
		try {
			if (await this.cacheService.get<boolean>(appliedKey)) {
				Logger.debug({userId: user.id, idempotencyKey}, 'Gift trial extension already applied after lock acquisition');
				return {kind: 'already_applied'};
			}
			const subscription = await this.stripe.subscriptions.retrieve(user.stripeSubscriptionId);
			Logger.debug(
				{
					userId: user.id,
					subscriptionId: user.stripeSubscriptionId,
					retrievedTrialEnd: subscription.trial_end,
				},
				'Retrieved Stripe subscription before gift trial extension',
			);
			const currentTrialEnd = subscription.trial_end;
			const item = getPrimarySubscriptionItem(subscription);
			const currentPeriodEnd = getSubscriptionItemPeriodEndUnix(item);
			const nowMs = Date.now();
			const baseUnix = isGiftTrialRunning(subscription, nowMs) ? currentTrialEnd : currentPeriodEnd;
			Logger.debug(
				{
					userId: user.id,
					subscriptionId: user.stripeSubscriptionId,
					currentTrialEnd,
					currentPeriodEnd,
					baseUnix,
					durationType,
					durationQuantity,
				},
				'Computed Stripe gift trial extension base timestamp',
			);
			if (!baseUnix) {
				throw new StripeError('Subscription has no trial_end or current_period_end');
			}
			const baseDate = new Date(baseUnix * 1000);
			const newTrialEnd = addGiftCodeDuration(baseDate, durationType, durationQuantity);
			if (newTrialEnd === null) {
				throw new StripeError('Gift duration must be greater than zero when extending subscription trial');
			}
			if (isPastStripeTrialLimit(newTrialEnd.getTime(), nowMs)) {
				return {kind: 'past_trial_limit'};
			}
			const newTrialEndUnix = Math.floor(newTrialEnd.getTime() / 1000);
			Logger.debug(
				{
					userId: user.id,
					subscriptionId: user.stripeSubscriptionId,
					baseDate,
					newTrialEnd,
					newTrialEndUnix,
				},
				'Computed new Stripe trial end for gift extension',
			);
			const stripeIdempotencyKey = `gift_trial_extend:${user.id}:${idempotencyKey}`;
			const trialExtendedSubscription = await this.stripe.subscriptions.update(
				user.stripeSubscriptionId,
				{
					trial_end: newTrialEndUnix,
					proration_behavior: 'none',
					metadata: buildGiftTrialMetadata(subscription, idempotencyKey, baseUnix, newTrialEndUnix, nowMs),
				},
				{idempotencyKey: stripeIdempotencyKey},
			);
			await mirrorSubscription(
				trialExtendedSubscription,
				user.id,
				'Mirror upsert failed after Stripe write; reconciler will heal',
			);
			Logger.debug(
				{
					userId: user.id,
					subscriptionId: user.stripeSubscriptionId,
					stripeIdempotencyKey,
					newTrialEndUnix,
				},
				'Updated Stripe subscription trial end from gift extension',
			);
			await this.cacheService.set(appliedKey, true, seconds('365 days'));
			Logger.debug({userId: user.id, idempotencyKey, appliedKey}, 'Gift trial applied sentinel set');
			await this.confirmGiftApplied(trialExtendedSubscription, newTrialEndUnix);
			Logger.debug(
				{
					userId: user.id,
					subscriptionId: user.stripeSubscriptionId,
					baseDate,
					newTrialEnd,
					durationType,
					durationQuantity,
					idempotencyKey,
				},
				'Extended subscription with gift trial period',
			);
			return {kind: 'extended', subscription: trialExtendedSubscription};
		} catch (error: unknown) {
			Logger.error(
				{error, userId: user.id, subscriptionId: user.stripeSubscriptionId, idempotencyKey},
				'Failed to extend subscription with gift trial',
			);
			const message = error instanceof Error ? error.message : 'Failed to extend subscription with gift';
			throw new StripeError(message);
		} finally {
			if (userLockToken) {
				await this.releaseUserTrialLock(userLockKey, userLockToken, user.id);
			}
			await this.cacheService.delete(inflightKey);
			Logger.debug(
				{
					userId: user.id,
					idempotencyKey,
					inflightKey,
					lockReleased: Boolean(userLockToken),
				},
				'Finished Stripe gift trial extension cleanup',
			);
		}
	}

	private static readonly CURRENT_PRICE_CACHE_TTL_SECONDS = seconds('5 minutes');
	private static readonly LIST_PRICE_CACHE_TTL_SECONDS = seconds('1 hour');
	private static readonly PRICE_CACHE_PRODUCE_TIMEOUT_MS = 90000;
	private static readonly LIST_PRICE_SWITCH_LOCK_TTL_SECONDS = seconds('30 seconds');
	private static readonly USER_TRIAL_LOCK_TTL_SECONDS = seconds('30 seconds');
	private static readonly USER_TRIAL_LOCK_MAX_WAIT_MS = 15000;
	private static readonly USER_TRIAL_LOCK_RETRY_DELAY_MS = 100;

	private async acquireUserTrialLock(lockKey: string, userId: UserID): Promise<string | null> {
		const startTime = Date.now();
		while (Date.now() - startTime < StripeSubscriptionService.USER_TRIAL_LOCK_MAX_WAIT_MS) {
			const token = await this.cacheService.acquireLock(lockKey, StripeSubscriptionService.USER_TRIAL_LOCK_TTL_SECONDS);
			if (token) {
				return token;
			}
			await new Promise<void>((resolve) => {
				const timeout = setTimeout(resolve, StripeSubscriptionService.USER_TRIAL_LOCK_RETRY_DELAY_MS);
				timeout.unref?.();
			});
		}
		Logger.warn({userId, lockKey}, 'Timed out waiting for user trial extension lock');
		return null;
	}

	private async releaseUserTrialLock(lockKey: string, token: string, userId: UserID): Promise<void> {
		try {
			const released = await this.cacheService.releaseLock(lockKey, token);
			if (!released) {
				Logger.warn({userId, lockKey}, 'User trial extension lock token no longer matched on release');
			}
		} catch (error) {
			Logger.error({error, userId, lockKey}, 'Failed to release user trial extension lock');
		}
	}

	private getBillingCycleFromInterval(interval: string): RecurringBillingCycle | null {
		if (interval === 'month') {
			return 'monthly';
		}
		if (interval === 'year') {
			return 'yearly';
		}
		return null;
	}
}

const MANDATE_PAYMENT_METHOD_TYPES: ReadonlySet<string> = new Set(['pix', 'upi']);

function isMandatePaidSubscription(subscription: Stripe.Subscription): boolean {
	const paymentMethod = subscription.default_payment_method;
	if (paymentMethod && typeof paymentMethod === 'object' && MANDATE_PAYMENT_METHOD_TYPES.has(paymentMethod.type)) {
		return true;
	}
	const options = subscription.payment_settings?.payment_method_options;
	if (options?.pix || options?.upi) {
		return true;
	}
	return (subscription.payment_settings?.payment_method_types ?? []).some((type) =>
		MANDATE_PAYMENT_METHOD_TYPES.has(type),
	);
}