import { Platform } from "react-native";
import Purchases, { type CustomerInfo, type PurchasesOffering } from "react-native-purchases";

const API_KEY = process.env.EXPO_PUBLIC_REVENUECAT_API_KEY;

let configuredForRestaurantId: string | null = null;

// appUserID is the restaurant id — the backend webhook (POST
// /subscription/webhook) maps RevenueCat's app_user_id straight to
// subscriptions.restaurant_id, so these must always match.
export function configurePurchases(restaurantId: string) {
  if (!API_KEY) {
    console.warn("EXPO_PUBLIC_REVENUECAT_API_KEY missing — purchases disabled");
    return;
  }
  if (configuredForRestaurantId === restaurantId) return;

  Purchases.configure({ apiKey: API_KEY, appUserID: restaurantId });
  if (Platform.OS !== "web") {
    Purchases.setLogLevel(__DEV__ ? Purchases.LOG_LEVEL.DEBUG : Purchases.LOG_LEVEL.WARN);
  }
  configuredForRestaurantId = restaurantId;
}

export async function getCurrentOffering(): Promise<PurchasesOffering | null> {
  const offerings = await Purchases.getOfferings();
  return offerings.current;
}

export async function getCustomerInfo(): Promise<CustomerInfo> {
  return Purchases.getCustomerInfo();
}

// Checking by exact entitlement identifier is fragile — RevenueCat's
// dashboard let the identifier get created with a non-ASCII character
// ("Menul⁚io Pro" uses U+2024, not a plain period), which silently never
// matched a hardcoded string. This app only ever grants one entitlement,
// so "any active entitlement" is Pro and doesn't depend on that string.
export function isProActive(info: CustomerInfo): boolean {
  return Object.keys(info.entitlements.active).length > 0;
}

export function getActiveEntitlement(info: CustomerInfo) {
  const [first] = Object.values(info.entitlements.active);
  return first ?? null;
}
