/**
 * Resolve Stripe PaymentIntent / SetupIntent id for status sync after redirect.
 */
export function intentIdFromClientSecret(clientSecret?: string | null): string | null {
  if (!clientSecret) {
    return null;
  }
  const parts = clientSecret.split("_secret_");
  const id = parts[0]?.trim();
  if (!id) {
    return null;
  }
  if (id.startsWith("pi_") || id.startsWith("seti_")) {
    return id;
  }
  return null;
}

export function resolvePaymentIntentIdForRegistration(
  registrationId: string,
  options?: {
    paymentIntent?: string | null;
    setupIntent?: string | null;
    paymentIntentClientSecret?: string | null;
    setupIntentClientSecret?: string | null;
  }
): string | null {
  if (options?.paymentIntent) {
    return options.paymentIntent;
  }
  if (options?.setupIntent) {
    return options.setupIntent;
  }

  const fromPiSecret = intentIdFromClientSecret(options?.paymentIntentClientSecret);
  if (fromPiSecret) {
    return fromPiSecret;
  }

  const fromSiSecret = intentIdFromClientSecret(options?.setupIntentClientSecret);
  if (fromSiSecret) {
    return fromSiSecret;
  }

  if (typeof window === "undefined") {
    return null;
  }

  const storedIntent = sessionStorage.getItem(`payment_intent_${registrationId}`);
  if (storedIntent) {
    return storedIntent;
  }

  const storedSecret = sessionStorage.getItem(`payment_${registrationId}`);
  return intentIdFromClientSecret(storedSecret);
}
