import type { TCheckoutSessionExpanded, TLineItemExpanded } from '@blocklet/payment-types';
import type { CheckoutScenario } from '../types';

export function detectScenario(
  session: TCheckoutSessionExpanded | null | undefined,
  items: TLineItemExpanded[]
): CheckoutScenario {
  if (!session) return 'composite';

  const isSingleItem = items.length === 1;
  const isPaymentMode = session.mode === 'payment';
  const isSubscriptionMode = ['subscription', 'setup'].includes(session.mode || '');

  // Credit: single item + payment mode + product.type=credit + metadata.credit_config
  if (isSingleItem && isPaymentMode) {
    const item = items[0];
    const product = (item as any).price?.product;
    if (product?.type === 'credit' && (item as any).price?.metadata?.credit_config) {
      return 'credit-topup';
    }
  }

  // Subscription: single item + subscription/setup + no cross-sell
  if (isSingleItem && isSubscriptionMode && !items.some((i: any) => i.cross_sell)) {
    return 'subscription';
  }

  // Default: composite
  return 'composite';
}
