/**
 * BillingProvider — React context for @simpli/billing.
 *
 * Wrap your app (or a section of it) with <BillingProvider> to configure
 * the API connection. All billing hooks read from this context.
 *
 * Auth is handled server-side by your Next.js Route Handlers — you do NOT
 * pass any tokens here. Set apiBaseUrl to the billing proxy prefix in your app.
 *
 * Usage:
 *   <BillingProvider apiBaseUrl="/api">
 *     <PricingPage productId="crochet-patterns" />
 *   </BillingProvider>
 *
 * Your Next.js app must expose these Route Handlers under apiBaseUrl:
 *   GET  /api/billing/products/[slug]/          → public (no auth needed)
 *   POST /api/billing/offer-checkout/            → calls fetchDjangoServiceToken + proxyBillingRequest
 *   POST /api/billing/subscribe-free/            → same
 *   POST /api/billing/offer-portal/              → same
 *   GET  /api/billing/subscription/current/      → same
 */

import React, { createContext, useContext, useMemo } from "react";
import type { BillingConfig } from "../types";
import { BillingApiClient } from "../utils/api";

interface BillingContextValue {
  client: BillingApiClient;
  config: BillingConfig;
}

const BillingContext = createContext<BillingContextValue | null>(null);

export interface BillingProviderProps extends BillingConfig {
  children: React.ReactNode;
}

export function BillingProvider({
  children,
  ...config
}: BillingProviderProps) {
  const value = useMemo(() => {
    const client = new BillingApiClient(config);
    return { client, config };
  }, [config.apiBaseUrl]);

  return (
    <BillingContext.Provider value={value}>
      {children}
    </BillingContext.Provider>
  );
}

export function useBillingContext(): BillingContextValue {
  const ctx = useContext(BillingContext);
  if (!ctx) {
    throw new Error(
      "useBillingContext must be used within a <BillingProvider>"
    );
  }
  return ctx;
}
