export const STRIPE_CHECKOUT_SYNC_CHANNEL = "mawidi-stripe-checkout";
export const STRIPE_CHECKOUT_SYNC_STORAGE_KEY =
  "mawidi:stripe-checkout:sync";

export interface StripeCheckoutSyncEvent {
  type: "subscription-updated";
  sessionId?: string;
  at: number;
}

export function openHostedCheckoutWindow(): Window | null {
  if (typeof window === "undefined") {
    return null;
  }

  const checkoutWindow = window.open("about:blank", "_blank");

  if (checkoutWindow) {
    try {
      checkoutWindow.opener = null;
    } catch {
      // Ignore opener assignment failures; redirect fallback still works.
    }
  }

  return checkoutWindow;
}

export function redirectHostedCheckout(
  checkoutWindow: Window | null,
  url: string,
): boolean {
  if (checkoutWindow && !checkoutWindow.closed) {
    checkoutWindow.location.href = url;
    checkoutWindow.focus();
    return true;
  }

  if (typeof window !== "undefined") {
    window.location.href = url;
  }

  return false;
}

export function closeHostedCheckoutWindow(
  checkoutWindow: Window | null,
): void {
  if (checkoutWindow && !checkoutWindow.closed) {
    checkoutWindow.close();
  }
}

export function broadcastStripeCheckoutSync(sessionId?: string): void {
  if (typeof window === "undefined") {
    return;
  }

  const event: StripeCheckoutSyncEvent = {
    type: "subscription-updated",
    sessionId,
    at: Date.now(),
  };

  if ("BroadcastChannel" in window) {
    try {
      const channel = new BroadcastChannel(STRIPE_CHECKOUT_SYNC_CHANNEL);
      channel.postMessage(event);
      channel.close();
    } catch {
      // Fallback to storage events below.
    }
  }

  try {
    window.localStorage.setItem(
      STRIPE_CHECKOUT_SYNC_STORAGE_KEY,
      JSON.stringify(event),
    );
  } catch {
    // Ignore storage failures; BroadcastChannel may already have succeeded.
  }
}

export function parseStripeCheckoutSyncEvent(
  rawValue: string | null | undefined,
): StripeCheckoutSyncEvent | null {
  if (!rawValue) {
    return null;
  }

  try {
    const parsed = JSON.parse(rawValue) as Partial<StripeCheckoutSyncEvent>;

    if (
      parsed.type !== "subscription-updated" ||
      typeof parsed.at !== "number"
    ) {
      return null;
    }

    return {
      type: parsed.type,
      sessionId: parsed.sessionId,
      at: parsed.at,
    };
  } catch {
    return null;
  }
}
