// lib/api/billingApi.ts
// Client-facing billing calls. Uses the same clientPortalToken as clientPortalApi.

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:300/api";

function clientToken(): string {
  if (typeof window === "undefined") return "";
  return localStorage.getItem("clientPortalToken") || "";
}

async function call<T = any>(path: string, method: "GET" | "POST" = "GET"): Promise<T> {
  const token = clientToken();
  const res = await fetch(`${API_BASE}${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json?.message || `Error ${res.status}`);
  return json as T;
}

export interface BillingStatus {
  active: boolean;
  status: string;
  plan: string | null;
  is_free?: boolean;
  billing_enabled?: boolean;
  requires_payment?: boolean;
  access_allowed?: boolean;
  current_period_end: string | null;
  price_amount: number | null;
  price_currency: string | null;
  price_interval: string | null;
  currency: string;
}

export const billingApi = {
  getStatus: () =>
    call<{ success: boolean; data: BillingStatus }>("/client-portal/billing/status", "GET"),

  createCheckoutSession: () =>
    call<{ success: boolean; data: { url: string; session_id: string } }>(
      "/client-portal/billing/create-checkout-session",
      "POST",
    ),
};
