import { loadStripe, type Stripe } from "@stripe/stripe-js";

export function getStripePublishableKey(): string {
  return process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY || "";
}

/**
 * Load Stripe.js for Connect direct charges (platform publishable key + connected account).
 */
export function loadStripeConnect(
  publishableKey: string,
  stripeAccountId?: string | null
): Promise<Stripe | null> {
  if (!publishableKey || !stripeAccountId) {
    return Promise.resolve(null);
  }

  return loadStripe(publishableKey, { stripeAccount: stripeAccountId });
}

export function extractClientSecretFromPayment(paymentData: unknown): string | null {
  if (!paymentData || typeof paymentData !== "object") {
    return null;
  }

  const data = paymentData as Record<string, unknown>;
  const response = data.response as Record<string, unknown> | undefined;
  const secret = response?.client_secret;

  return typeof secret === "string" && secret.length > 0 ? secret : null;
}

export function extractStripeAccountFromPayment(paymentData: unknown): string | null {
  if (!paymentData || typeof paymentData !== "object") {
    return null;
  }

  const data = paymentData as Record<string, unknown>;
  const fromTop = data.stripe_account_id;
  const fromMeta = (data.response as Record<string, unknown> | undefined)?.metadata as
    | Record<string, unknown>
    | undefined;

  const id = (fromTop || fromMeta?.stripe_account_id) as string | undefined;

  return id && String(id).trim() !== "" ? String(id).trim() : null;
}

export function stripeAccountSessionKey(registrationId: string): string {
  return `stripe_account_${registrationId}`;
}

export function readStripeAccountFromSession(registrationId: string): string | null {
  if (typeof window === "undefined") {
    return null;
  }

  return sessionStorage.getItem(stripeAccountSessionKey(registrationId));
}

export function writeStripeAccountToSession(
  registrationId: string,
  stripeAccountId: string | null | undefined
): void {
  if (typeof window === "undefined" || !stripeAccountId) {
    return;
  }

  sessionStorage.setItem(stripeAccountSessionKey(registrationId), stripeAccountId);
}
