import { registerPlugin } from "@capacitor/core";
import { Browser } from "@capacitor/browser";
import { platformRuntime } from "./runtime.js";

const PRODUCT_ID = "pro_multi_account";
const STATES = new Set(["activated", "pending", "canceled", "unavailable", "not_owned"]);

export function createProBillingAdapter({ isNative = platformRuntime.isAndroid, plugin, browser = Browser } = {}) {
  const native = plugin ?? (isNative ? registerPlugin("ProBilling") : null);
  return {
    async getProduct() {
      if (!native?.getProduct) return unavailableProduct();
      try {
        const value = await native.getProduct();
        return value?.productId === PRODUCT_ID && typeof value.available === "boolean"
          && (value.localizedPrice === null || typeof value.localizedPrice === "string")
          ? { productId: PRODUCT_ID, localizedPrice: value.localizedPrice, available: value.available }
          : unavailableProduct();
      } catch { return unavailableProduct(); }
    },
    purchase(binding) { return invoke(native, "purchase", binding); },
    restore(binding) { return invoke(native, "restore", binding); },
    async openManagement() {
      try {
        await browser.open({ url: "https://play.google.com/store/account/orderhistory" });
        return { opened: true };
      } catch { return { opened: false }; }
    },
  };
}

async function invoke(plugin, method, binding) {
  if (!plugin?.[method] || !validBinding(binding)) return { state: "unavailable" };
  try {
    const value = await plugin[method]({ backendKeyThumbprint: binding.backendKeyThumbprint, challengeHash: binding.challengeHash });
    if (!STATES.has(value?.state)) return { state: "unavailable" };
    if (value.state === "activated") {
      if (typeof value.certificate !== "string" || typeof value.expiresAt !== "string") return { state: "unavailable" };
      return { state: value.state, certificate: value.certificate, expiresAt: value.expiresAt };
    }
    return { state: value.state };
  } catch { return { state: "unavailable" }; }
}
function validBinding(value) { return /^[A-Za-z0-9_-]{43}$/.test(value?.backendKeyThumbprint ?? "") && /^[A-Za-z0-9_-]{43}$/.test(value?.challengeHash ?? ""); }
function unavailableProduct() { return { productId: PRODUCT_ID, localizedPrice: null, available: false }; }

export const proBilling = createProBillingAdapter();
