/**
 * API client for billing endpoints.
 */

import type {
  BillingConfig,
  BillingProduct,
  CachedSubscriptionState,
  CheckoutResult,
  FreeSubscriptionResult,
  PlanChangePreview,
  PortalResult,
  SubscriptionInfo,
  UsageMap,
} from "../types";
import { billingErrorMessage } from "./error-message";
import { currentGaIds } from "./ga-ids";

export class BillingApiClient {
  private config: BillingConfig;

  constructor(config: BillingConfig) {
    this.config = config;
  }

  private get fetcher() {
    return this.config.fetcher ?? fetch.bind(globalThis);
  }

  private get headers(): HeadersInit {
    return { "Content-Type": "application/json" };
  }

  /** Fetch a public billing product by slug. */
  async getProduct(slug: string): Promise<BillingProduct> {
    const url = `${this.config.apiBaseUrl}/billing/products/${slug}/`;
    const resp = await this.fetcher(url, {
      headers: this.headers,
    });
    if (!resp.ok) {
      throw new Error(`Failed to fetch product "${slug}": ${resp.status}`);
    }
    return resp.json();
  }

  /** Create a checkout session for an offer. */
  async createCheckout(params: {
    offerId: string;
    successUrl: string;
    cancelUrl: string;
    quantity?: number;
  }): Promise<CheckoutResult> {
    const url = `${this.config.apiBaseUrl}/billing/offer-checkout/`;
    const ga = currentGaIds();
    const resp = await this.fetcher(url, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({
        offer_id: params.offerId,
        success_url: params.successUrl,
        cancel_url: params.cancelUrl,
        quantity: params.quantity ?? 1,
        // For the subscription's conversion, sent from the server.
        ...(ga && { analytics: ga }),
      }),
    });
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(billingErrorMessage(data, `Checkout failed: ${resp.status}`));
    }
    return resp.json();
  }

  /** Subscribe to a free offer (no billing provider). */
  async subscribeFree(offerId: string): Promise<FreeSubscriptionResult> {
    const url = `${this.config.apiBaseUrl}/billing/subscribe-free/`;
    const resp = await this.fetcher(url, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({ offer_id: offerId }),
    });
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(billingErrorMessage(data, `Free signup failed: ${resp.status}`));
    }
    return resp.json();
  }

  /** Create a customer portal session. */
  async createPortal(returnUrl: string): Promise<PortalResult> {
    const url = `${this.config.apiBaseUrl}/billing/offer-portal/`;
    const resp = await this.fetcher(url, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({ return_url: returnUrl }),
    });
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(billingErrorMessage(data, `Portal session failed: ${resp.status}`));
    }
    return resp.json();
  }

  /**
   * Eagerly sync subscription state after Stripe checkout redirect.
   * Call this from your success_url page to avoid waiting for the webhook.
   */
  /** What choosing an offer will do, without doing it (crochet_patterns-anw61). */
  async previewPlanChange(offerId: string): Promise<PlanChangePreview> {
    const url = `${this.config.apiBaseUrl}/billing/plan-change-preview/`;
    const resp = await this.fetcher(url, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({ offer_id: offerId }),
    });
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(billingErrorMessage(data, `Plan preview failed: ${resp.status}`));
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const raw: any = await resp.json();
    const cur = raw.current_offer ?? raw.currentOffer ?? null;
    return {
      mode: raw.mode,
      offerId: raw.offer_id ?? raw.offerId ?? offerId,
      amountDue: raw.amount_due ?? raw.amountDue ?? null,
      currency: raw.currency ?? "usd",
      effectiveAt: raw.effective_at ?? raw.effectiveAt ?? null,
      trialDays: raw.trial_days ?? raw.trialDays ?? 0,
      currentOffer: cur
        ? { slug: cur.slug, name: cur.name, isListed: (cur.is_listed ?? cur.isListed) !== false }
        : null,
    };
  }

  /** `sessionId` is the checkout session from the success URL
   * ({CHECKOUT_SESSION_ID}): it sends the sync straight to the checkout that
   * was paid, not to whichever customer the team resolves to first
   * (crochet_patterns-eq11). */
  async successSync(params: { sessionId?: string | null; productSlug?: string | null } = {}): Promise<CachedSubscriptionState | null> {
    const url = `${this.config.apiBaseUrl}/billing/success-sync/`;
    const body: Record<string, string> = {};
    if (params.sessionId) body.session_id = params.sessionId;
    if (params.productSlug) body.product_slug = params.productSlug;
    const resp = await this.fetcher(url, {
      method: "POST",
      headers: this.headers,
      ...(Object.keys(body).length > 0 && { body: JSON.stringify(body) }),
    });
    if (resp.status === 404) {
      return null;
    }
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(billingErrorMessage(data, `Success sync failed: ${resp.status}`));
    }
    return resp.json();
  }

  /** Per-product usage map for the current user/team — {feature_key:
   * {used, limit}}. Graceful: 200 {} when no adapter / no sub / errors.
   * startsim-h14 — feeds CurrentPlanCard progress bars.
   */
  async getUsage(slug: string): Promise<UsageMap> {
    const url = `${this.config.apiBaseUrl}/billing/usage/${slug}/`;
    const resp = await this.fetcher(url, { headers: this.headers });
    if (!resp.ok) {
      // Treat any non-2xx as "no data" — usage failures must not block the
      // page. UI hides the bars when the map is empty.
      return {};
    }
    return (await resp.json()) as UsageMap;
  }

  /**
   * Get current user's subscription. Pass the app's product slug: a team can
   * hold subscriptions to several products, and without it the backend returns
   * the newest one for ANY product (startsim-oyr3a.2).
   */
  async getSubscription(productSlug?: string): Promise<SubscriptionInfo | null> {
    const query = productSlug ? `?product=${encodeURIComponent(productSlug)}` : "";
    const url = `${this.config.apiBaseUrl}/billing/subscription/current/${query}`;
    const resp = await this.fetcher(url, {
      headers: this.headers,
    });
    if (resp.status === 404) {
      return null; // No active subscription
    }
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(billingErrorMessage(data, `Failed to fetch subscription: ${resp.status}`));
    }
    return this.normalizeSubscription(await resp.json());
  }

  /**
   * The `subscription/current/` endpoint is polymorphic: the DB path returns
   * the rich SubscriptionInfo (nested `offer` object), but the Redis cache path
   * returns the flat CachedSubscriptionState (offerId/offerSlug/productSlug, no
   * nested `offer`). The UI reads `subscription.offer.*` unconditionally, so a
   * flat payload white-screens the page. This guard hydrates the flat shape
   * into the rich one by resolving the offer from the product; if it can't, it
   * returns null ("no usable subscription") rather than letting the page crash.
   * Defense-in-depth against backend contract drift. startsim — billing-offer-null.
   */
  private async normalizeSubscription(raw: unknown): Promise<SubscriptionInfo | null> {
    if (!raw || typeof raw !== "object") return null;
    const r = raw as Record<string, unknown>;

    // Already the rich shape — nested offer object present.
    if (r.offer && typeof r.offer === "object") return raw as SubscriptionInfo;

    // Flat cache shape: try to hydrate the offer from the product.
    const productSlug = r.productSlug as string | undefined;
    const offerId = r.offerId as string | undefined;
    const offerSlug = r.offerSlug as string | undefined;
    const status = r.status as string | undefined;
    // No status or nothing to resolve an offer from → not a renderable sub.
    if (!status || status === "none" || !productSlug || (!offerId && !offerSlug)) {
      return null;
    }

    try {
      const product = await this.getProduct(productSlug);
      const offer = product.offers.find(
        (o) => (offerId && o.id === offerId) || (offerSlug && o.slug === offerSlug)
      );
      if (!offer) return null;
      const toIso = (v: unknown): string | null => {
        if (v == null) return null;
        // Cache stores unix seconds; SubscriptionInfo expects ISO strings.
        if (typeof v === "number") return new Date(v * 1000).toISOString();
        if (typeof v === "string") return v;
        return null;
      };
      return {
        id: (r.subscriptionId as string) ?? offer.id,
        offer,
        status: status as SubscriptionInfo["status"],
        currentPeriodStart: toIso(r.currentPeriodStart),
        currentPeriodEnd: toIso(r.currentPeriodEnd),
        cancelAtPeriodEnd: Boolean(r.cancelAtPeriodEnd),
        trialEnd: toIso(r.trialEnd),
        conversionByServer: Boolean(r.conversionByServer),
      };
    } catch {
      // Product fetch failed — degrade to "no subscription" instead of crashing.
      return null;
    }
  }
}
