import assert from "node:assert/strict";
import test from "node:test";
import { createProEntitlementController } from "./useProEntitlement.js";

test("controller refreshes, activates purchase, and discards certificate from public state", async () => {
  const activated = [];
  const api = { async status() { return { tier: activated.length ? "pro" : "free", maxAccounts: activated.length ? 5 : 1 }; }, async challenge() { return { challenge: "opaque", backendKeyThumbprint: "a".repeat(43), challengeHash: "b".repeat(43) }; }, async activate(challenge, certificate) { activated.push([challenge, certificate]); } };
  const controller = createProEntitlementController({ api, billing: { async purchase() { return { state: "activated", certificate: "signed", expiresAt: "later" }; } } });
  await controller.refresh(); assert.equal(controller.getState().tier, "free");
  assert.equal((await controller.purchase()).state, "activated"); assert.deepEqual(activated, [["opaque", "signed"]]);
  assert.equal(controller.getState().tier, "pro"); assert.equal(JSON.stringify(controller.getState()).includes("signed"), false);
});

test("expired activation retries once with restore while pending and cancellation do not activate", async () => {
  let challenges = 0, activations = 0, restores = 0;
  const api = { async status() { return { tier: "free", maxAccounts: 1 }; }, async challenge() { challenges++; return { challenge: `opaque-${challenges}`, backendKeyThumbprint: "a".repeat(43), challengeHash: "b".repeat(43) }; }, async activate() { activations++; if (activations === 1) throw new Error("entitlement_challenge_expired"); } };
  const billing = { async purchase() { return { state: "activated", certificate: "first", expiresAt: "later" }; }, async restore() { restores++; return { state: "activated", certificate: "second", expiresAt: "later" }; } };
  const controller = createProEntitlementController({ api, billing });
  assert.equal((await controller.purchase()).state, "activated"); assert.equal(challenges, 2); assert.equal(restores, 1); assert.equal(activations, 2);
  for (const state of ["pending", "canceled"]) { const quiet = createProEntitlementController({ api, billing: { async purchase() { return { state }; } } }); assert.equal((await quiet.purchase()).state, state); }
});

test("backend disconnect is a safe unavailable state", async () => {
  const controller = createProEntitlementController({ api: { async status() { throw new Error("pc_unreachable"); } }, billing: {} });
  await controller.refresh(); assert.equal(controller.getState().connection, "unavailable");
});
