import assert from "node:assert/strict";
import { test } from "node:test";
import { webcrypto } from "node:crypto";

if (!globalThis.crypto) globalThis.crypto = webcrypto;
if (!globalThis.btoa) globalThis.btoa = value => Buffer.from(value, "binary").toString("base64");
if (!globalThis.atob) globalThis.atob = value => Buffer.from(value, "base64").toString("binary");

const { createHandler } = await import("../src/worker.mjs");

class MemoryKv {
  values = new Map();
  getCount = 0;
  putCount = 0;
  failGetAt = null;
  failPutAt = null;
  failPutsFrom = null;
  failAllPuts = false;
  constructor(marker = "smartcut64-license-state:test:00000000000000000000000000000020:v1") {
    if (marker !== null) this.values.set("system:namespace-marker:v1", marker);
  }
  async get(key, type) {
    ++this.getCount;
    if (this.failGetAt === this.getCount) throw new Error("test_kv_get_failure");
    if (!this.values.has(key)) return null;
    const value = this.values.get(key);
    return type === "json" ? JSON.parse(value) : value;
  }
  async put(key, value) {
    ++this.putCount;
    if (this.failAllPuts || this.failPutAt === this.putCount ||
        (this.failPutsFrom !== null && this.putCount >= this.failPutsFrom))
      throw new Error("test_kv_put_failure");
    this.values.set(key, String(value));
  }
  async list({ prefix = "" } = {}) {
    return {
      keys: [...this.values.keys()].filter(key => key.startsWith(prefix)).map(name => ({ name })),
      list_complete: true
    };
  }
}

async function keys() {
  const pair = await crypto.subtle.generateKey(
    { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
    true, ["sign", "verify"]);
  const privateBytes = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
  const privatePem = `-----BEGIN PRIVATE KEY-----\n${Buffer.from(privateBytes).toString("base64").match(/.{1,64}/g).join("\n")}\n-----END PRIVATE KEY-----`; // gitleaks:allow - ephemeral test key generated in memory
  const publicJwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
  const publicModulusHex = Buffer.from(publicJwk.n, "base64url").toString("hex");
  const publicModulusSha256 = Buffer.from(await crypto.subtle.digest(
    "SHA-256", Buffer.from(publicModulusHex, "hex"))).toString("hex");
  return { pair, privatePem, publicModulusHex, publicModulusSha256 };
}

function env(signing) {
  return {
    LICENSE_STATE: new MemoryKv(), SMARTCUT_PRIVATE_KEY_PEM: signing.privatePem,
    SMARTCUT_LICENSE_PUBLIC_MODULUS_HEX: signing.publicModulusHex,
    LEMON_WEBHOOK_SECRET: "test-webhook-secret", // gitleaks:allow - non-production test fixture
    CF_VERSION_METADATA: { id: "test-worker-version" },
    LEMON_LICENSE_API_BASE: "https://licenses.test/v1/licenses",
    LEMON_STORE_ID: "10", LEMON_PRODUCT_ID: "20", LEMON_VARIANT_IDS: "30,31",
    LICENSE_RATE_LIMIT: { async limit() { return { success: true }; } },
    ACTOR_RATE_LIMIT: { async limit() { return { success: true }; } }
  };
}

function testHandler(signing, options = {}) {
  return createHandler({
    ...options,
    trustedPublicModulusSha256ByProduct: { "20": signing.publicModulusSha256 },
    trustedCommerceByProduct: {
      "20": { apiBase: "https://licenses.test/v1/licenses", store: "10", variants: ["30", "31"],
        licenseStateMarker: "smartcut64-license-state:test:00000000000000000000000000000020:v1" }
    }
  });
}

function lemonFetch({ productId = 20, control = {} } = {}) {
  let activations = 0;
  const calls = [];
  const fetchImpl = async (url, options) => {
    const operation = new URL(url).pathname.split("/").pop();
    const fields = Object.fromEntries(new URLSearchParams(options.body));
    calls.push({ operation, fields });
    const meta = { store_id: 10, product_id: productId, variant_id: 30, order_id: 40,
      order_item_id: 50, customer_name: "Test Customer", customer_email: "buyer@example.com" };
    if (operation === "activate") {
      const suffix = String(++activations).padStart(12, "0");
      return Response.json({ activated: true, error: null,
        license_key: { id: 60 },
        instance: { id: control.instanceId ?? `00000000-0000-4000-8000-${suffix}` }, meta });
    }
    if (operation === "validate") {
      if (control.unrelatedNotFoundForInstance && fields.instance_id)
        return Response.json({ error: "Unexpected upstream route failure." }, { status: 404 });
      if (control.notFoundForInstance && fields.instance_id)
        return Response.json({ error: "Instance not found." }, { status: 404 });
      return Response.json({
        valid: !(control.validateAllFalse || (control.validateExistingFalse && fields.instance_id) ||
          (control.validateKeyFalse && !fields.instance_id)), error: null,
        license_key: { id: 60, status: "active" },
        instance: fields.instance_id ? { id: fields.instance_id } : null, meta });
    }
    if (operation === "deactivate") {
      if (control.throwOnDeactivate) throw new Error("test_deactivation_failure");
      if (control.notFoundForDeactivate)
        return Response.json({ error: "Instance not found." }, { status: 404 });
      const deactivationMeta = control.deactivationProductId === undefined
        ? meta : { ...meta, product_id: control.deactivationProductId };
      return Response.json({ deactivated: control.deactivated !== false, error: null,
        license_key: { id: control.deactivationLicenseId ?? 60 }, meta: deactivationMeta });
    }
    return Response.json({ error: "not found" }, { status: 404 });
  };
  return { fetchImpl, calls };
}

function post(path, body, headers = {}) {
  return new Request(`https://licensing.example${path}`, { method: "POST",
    headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) });
}

// Exact state-routing decision used by the currently deployed v1 Worker.
// Pending records must select "block", never its fresh-activate branch, so v1
// remains a safe rollback target after candidate traffic.
function deployedV1ActivationRoute(record) {
  if (record && record.status === "revoked") return "block";
  if (record && record.status === "active") return "validate_existing";
  return "activate";
}

function decodeBase64Url(value) {
  return Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/"), "base64");
}

async function signedWebhook(secret, payload) {
  const text = JSON.stringify(payload);
  const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret),
    { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const signature = Buffer.from(await crypto.subtle.sign("HMAC", key,
    new TextEncoder().encode(text))).toString("hex");
  return new Request("https://licensing.example/v1/webhooks/lemon", { method: "POST",
    headers: { "content-type": "application/json", "x-signature": signature }, body: text });
}

test("activates the exact Lemon product and signs a compatible machine entitlement", async () => {
  const signing = await keys();
  const environment = env(signing);
  const lemon = lemonFetch();
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 200);
  const body = await result.json();
  assert.equal(body.ok, true);
  const [prefix, payloadSegment, signatureSegment] = body.entitlement.split(".");
  assert.equal(prefix, "SC64-1");
  const signedText = `${prefix}.${payloadSegment}`;
  assert.equal(await crypto.subtle.verify("RSASSA-PKCS1-v1_5", signing.pair.publicKey,
    decodeBase64Url(signatureSegment), new TextEncoder().encode(signedText)), true);
  const claims = decodeBase64Url(payloadSegment).toString("utf8");
  assert.match(claims, /product=SmartCut64/);
  assert.match(claims, /license_id=lemon-60/);
  assert.match(claims, /installation_id=0123456789abcdef0123456789abcdef/);
  assert.match(claims, /expires_unix=0/);
  assert.match(claims, /clean_export=1/);
  assert.equal(body.expires_unix, 0);
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate", "activate"]);
});

test("revalidates an existing installation without consuming another activation", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate", "activate", "validate"]);
});

test("serializes concurrent identical activations within one Worker isolate", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  const [first, second] = await Promise.all([
    handler.fetch(post("/v1/activate", body), environment),
    handler.fetch(post("/v1/activate", body), environment)
  ]);
  assert.equal(first.status, 200);
  assert.equal(second.status, 200);
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate", "activate", "validate"]);
  assert.equal(lemon.calls.filter(call => call.operation === "activate").length, 1);
});

test("revalidates a literal activation record written by the deployed v1 Worker", async () => {
  const signing = await keys(); const environment = env(signing);
  const licenseKey = "test-license-key";
  const installationId = "0123456789abcdef0123456789abcdef";
  const digest = Buffer.from(await crypto.subtle.digest(
    "SHA-256", new TextEncoder().encode(licenseKey))).toString("hex");
  const recordKey = `activation:${digest}:${installationId}`;
  environment.LICENSE_STATE.values.set(recordKey, JSON.stringify({
    schema: "smartcut64-lemon-activation-v1",
    status: "active",
    installation_id: installationId,
    instance_id: "00000000-0000-4000-8000-000000000001",
    license_id: "60",
    order_id: "40",
    customer_email: "buyer@example.com",
    customer_name: "Test Customer",
    created_at: "2026-01-01T00:00:00.000Z",
    updated_at: "2026-01-01T00:00:00.000Z"
  }));
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: licenseKey,
    email: "buyer@example.com", installation_id: installationId }), environment);
  assert.equal(result.status, 200);
  assert.equal(typeof (await result.json()).entitlement, "string");
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate"]);
  assert.equal(environment.LICENSE_STATE.putCount, 0);
});

test("an instance reported invalid is retired before a replacement activation", async () => {
  const signing = await keys(); const environment = env(signing);
  const control = {};
  const lemon = lemonFetch({ control });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  control.validateExistingFalse = true;
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "validate", "validate", "deactivate", "validate", "activate"]);
  assert.equal(lemon.calls[4].fields.instance_id,
    "00000000-0000-4000-8000-000000000001");
});

test("an already-gone active instance can be reconciled and activated again", async () => {
  const signing = await keys(); const environment = env(signing);
  const control = {};
  const lemon = lemonFetch({ control });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);

  control.notFoundForInstance = true;
  control.notFoundForDeactivate = true;
  const retry = await handler.fetch(post("/v1/activate", body), environment);
  assert.equal(retry.status, 200);
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "validate", "validate", "deactivate", "validate", "activate"]);
  assert.equal(lemon.calls[4].fields.instance_id,
    "00000000-0000-4000-8000-000000000001");
});

test("an unrelated Lemon 404 cannot be mistaken for an already-gone instance", async () => {
  const signing = await keys(); const environment = env(signing);
  const control = {};
  const lemon = lemonFetch({ control });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);

  control.unrelatedNotFoundForInstance = true;
  const retry = await handler.fetch(post("/v1/activate", body), environment);
  assert.equal(retry.status, 403);
  assert.equal((await retry.json()).code, "licence_not_valid");
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "validate"]);
  assert.equal(lemon.calls.filter(call => call.operation === "activate").length, 1);
});

test("an invalid or disabled existing licence cannot consume a duplicate activation", async () => {
  const signing = await keys(); const environment = env(signing);
  const control = {};
  const lemon = lemonFetch({ control });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);

  control.validateExistingFalse = true;
  control.validateKeyFalse = true;
  const disabled = await handler.fetch(post("/v1/activate", body), environment);
  assert.equal(disabled.status, 403);
  assert.equal((await disabled.json()).code, "licence_not_valid");
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "validate", "validate"]);
  const recordKey = [...environment.LICENSE_STATE.values.keys()]
    .find(key => key.startsWith("activation:"));
  assert.equal(JSON.parse(environment.LICENSE_STATE.values.get(recordKey)).status, "active");

  control.validateExistingFalse = false;
  control.validateKeyFalse = false;
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "validate", "validate", "validate"]);
});

test("uncertain cleanup of an invalid existing instance fails before replacement activation", async () => {
  const signing = await keys(); const environment = env(signing);
  const control = {};
  const lemon = lemonFetch({ control });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);

  control.validateExistingFalse = true;
  control.deactivated = false;
  const retry = await handler.fetch(post("/v1/activate", body), environment);
  assert.equal(retry.status, 503);
  assert.equal((await retry.json()).code, "activation_recovery_pending");
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "validate", "validate", "deactivate"]);
  const recordKey = [...environment.LICENSE_STATE.values.keys()]
    .find(key => key.startsWith("activation:"));
  assert.equal(JSON.parse(environment.LICENSE_STATE.values.get(recordKey)).status, "active");
});

test("a wrong-purchase deactivation response cannot authorize replacement activation", async () => {
  const signing = await keys(); const environment = env(signing);
  const control = {};
  const lemon = lemonFetch({ control });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);

  control.validateExistingFalse = true;
  control.deactivationProductId = 999;
  const retry = await handler.fetch(post("/v1/activate", body), environment);
  assert.equal(retry.status, 503);
  assert.equal((await retry.json()).code, "activation_recovery_pending");
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "validate", "validate", "deactivate"]);
  assert.equal(lemon.calls.filter(call => call.operation === "activate").length, 1);
});

test("a mistyped email cannot revoke an existing installation", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  assert.equal((await handler.fetch(post("/v1/activate", { ...body,
    email: "mistyped@example.com" }), environment)).status, 403);
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "validate", "validate"]);
});

test("native rate limits reject abusive requests before calling Lemon", async () => {
  const signing = await keys(); const environment = env(signing);
  environment.LICENSE_RATE_LIMIT = { async limit() { return { success: false }; } };
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 429);
  assert.equal(lemon.calls.length, 0);
});

test("missing rate-limit bindings fail closed before calling Lemon", async () => {
  const signing = await keys(); const environment = env(signing);
  delete environment.ACTOR_RATE_LIMIT;
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "service_not_configured");
  assert.equal(lemon.calls.length, 0);
});

test("any not-ready service configuration fails before Lemon activation", async t => {
  const signing = await keys();
  for (const [name, breakConfiguration] of [
    ["missing version metadata", environment => { delete environment.CF_VERSION_METADATA; }],
    ["missing webhook secret", environment => { delete environment.LEMON_WEBHOOK_SECRET; }]
  ]) {
    await t.test(name, async () => {
      const environment = env(signing);
      breakConfiguration(environment);
      const lemon = lemonFetch();
      const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
      const result = await handler.fetch(post("/v1/activate", {
        license_key: "test-license-key", email: "buyer@example.com",
        installation_id: "0123456789abcdef0123456789abcdef"
      }), environment);
      assert.equal(result.status, 503);
      assert.equal((await result.json()).code, "service_not_configured");
      assert.equal(lemon.calls.length, 0);
      assert.equal(environment.LICENSE_STATE.getCount, 0);
      assert.equal(environment.LICENSE_STATE.putCount, 0);
    });
  }
});

test("reports the Lemon activation limit as a device-limit conflict", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch();
  const fetchImpl = async (url, options) => {
    if (new URL(url).pathname.endsWith("/validate")) return lemon.fetchImpl(url, options);
    return Response.json({
      activated: false,
      error: "This license key has reached the activation limit.",
      license_key: { id: 60 },
      meta: {}
    }, { status: 400 });
  };
  const handler = testHandler(signing, { fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 409);
  const body = await result.json();
  assert.equal(body.code, "activation_limit_reached");
  assert.match(body.message, /maximum number of computers/i);
  const recordKey = [...environment.LICENSE_STATE.values.keys()]
    .find(key => key.startsWith("activation:"));
  assert.ok(recordKey);
  assert.equal(JSON.parse(environment.LICENSE_STATE.values.get(recordKey)).status, "deactivated");

  const retry = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(retry.status, 409);
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "validate"]);
});

test("an ambiguous activated response stays pending and cannot activate twice", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch({ control: { instanceId: "not-a-uuid" } });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };

  const first = await handler.fetch(post("/v1/activate", body), environment);
  assert.equal(first.status, 503);
  assert.equal((await first.json()).code, "activation_recovery_pending");
  const recordKey = [...environment.LICENSE_STATE.values.keys()]
    .find(key => key.startsWith("activation:"));
  assert.ok(recordKey);
  const pendingRecord = JSON.parse(environment.LICENSE_STATE.values.get(recordKey));
  assert.equal(pendingRecord.status, "revoked");
  assert.equal(pendingRecord.recovery_status, "activation_pending");
  assert.equal(deployedV1ActivationRoute(pendingRecord), "block");

  const retry = await handler.fetch(post("/v1/activate", body), environment);
  assert.equal(retry.status, 503);
  assert.equal((await retry.json()).code, "activation_recovery_pending");
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate", "activate"]);
});

test("maps other Lemon client rejections to an invalid licence", async () => {
  const signing = await keys(); const environment = env(signing);
  const fetchImpl = async () => Response.json({ activated: false,
    error: "License key not found." }, { status: 404 });
  const handler = testHandler(signing, { fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 403);
  assert.equal((await result.json()).code, "licence_not_valid");
});

test("reports Lemon API throttling as temporary rather than an invalid licence", async () => {
  const signing = await keys(); const environment = env(signing);
  const handler = testHandler(signing, {
    fetchImpl: async () => Response.json({ error: "Too Many Requests" }, { status: 429 })
  });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "upstream_rate_limited");
});

test("rejects malformed Lemon success payloads before issuing an entitlement", async () => {
  const signing = await keys(); const environment = env(signing);
  const calls = [];
  const fetchImpl = async url => {
    calls.push(new URL(url).pathname.split("/").pop());
    return Response.json({ valid: true, license_key: {}, instance: null,
      meta: { store_id: 10, product_id: 20, variant_id: 30, order_id: 40,
        customer_name: "Test Customer", customer_email: "buyer@example.com" } });
  };
  const handler = testHandler(signing, { fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 403);
  const body = await result.json();
  assert.equal(body.entitlement, undefined);
  assert.deepEqual(calls, ["validate"]);
  assert.equal(environment.LICENSE_STATE.putCount, 0);
});

test("a malformed signing key fails before Lemon or licence storage", async () => {
  const signing = await keys(); const environment = env(signing);
  environment.SMARTCUT_PRIVATE_KEY_PEM = "not a private key"; // gitleaks:allow - deliberate invalid-input fixture
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "service_not_configured");
  assert.equal(lemon.calls.length, 0);
  assert.equal(environment.LICENSE_STATE.getCount, 0);
  assert.equal(environment.LICENSE_STATE.putCount, 0);
});

test("readiness proves the signing key pair and licence-state binding without mutation", async () => {
  const signing = await keys(); const environment = env(signing);
  let fetchCount = 0;
  const handler = testHandler(signing,
    { fetchImpl: async () => { ++fetchCount; throw new Error("unexpected_fetch"); } });
  for (const path of ["/ready", "/health"]) {
    const result = await handler.fetch(new Request(`https://licensing.example${path}`), environment);
    assert.equal(result.status, 200);
    assert.deepEqual(await result.json(), {
      ok: true,
      ready: true,
      service: "smartcut64-licensing",
      schema: 2,
      version_id: "test-worker-version"
    });
  }
  assert.equal(fetchCount, 0);
  assert.equal(environment.LICENSE_STATE.getCount, 2);
  assert.equal(environment.LICENSE_STATE.putCount, 0);
});

test("a missing, wrong or unavailable licence-state marker fails closed before Lemon", async t => {
  const signing = await keys();
  const cases = [
    ["missing marker", environment => {
      environment.LICENSE_STATE.values.delete("system:namespace-marker:v1");
    }],
    ["wrong marker", environment => {
      environment.LICENSE_STATE.values.set("system:namespace-marker:v1",
        "smartcut64-license-state:production:b48acd15f08540abbdb7026cbdbb0319:v1");
    }],
    ["wrong physical test namespace", environment => {
      environment.LICENSE_STATE.values.set("system:namespace-marker:v1",
        "smartcut64-license-state:test:ffffffffffffffffffffffffffffffff:v1");
    }],
    ["KV read failure", environment => { environment.LICENSE_STATE.failGetAt = 1; }]
  ];
  for (const [name, breakState] of cases) {
    await t.test(name, async () => {
      const lemon = lemonFetch();
      const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });

      const readinessEnvironment = env(signing);
      breakState(readinessEnvironment);
      const ready = await handler.fetch(new Request("https://licensing.example/ready"),
        readinessEnvironment);
      assert.equal(ready.status, 503);
      assert.equal((await ready.json()).code, "service_not_ready");
      assert.equal(readinessEnvironment.LICENSE_STATE.putCount, 0);

      const activationEnvironment = env(signing);
      breakState(activationEnvironment);
      const activation = await handler.fetch(post("/v1/activate", {
        license_key: "test-license-key", email: "buyer@example.com",
        installation_id: "0123456789abcdef0123456789abcdef"
      }), activationEnvironment);
      assert.equal(activation.status, 503);
      assert.equal((await activation.json()).code, "service_not_configured");
      assert.equal(activationEnvironment.LICENSE_STATE.putCount, 0);
      assert.equal(lemon.calls.length, 0);
    });
  }
});

test("readiness fails generically for missing, malformed or mismatched signing material", async t => {
  const expected = await keys();
  const wrong = await keys();
  const cases = [
    ["missing private key", environment => { delete environment.SMARTCUT_PRIVATE_KEY_PEM; }],
    ["malformed private key", environment => { environment.SMARTCUT_PRIVATE_KEY_PEM = "not a private key"; }], // gitleaks:allow - deliberate invalid-input fixture
    ["wrong valid private key", environment => { environment.SMARTCUT_PRIVATE_KEY_PEM = wrong.privatePem; }],
    ["missing public key", environment => { delete environment.SMARTCUT_LICENSE_PUBLIC_MODULUS_HEX; }],
    ["malformed public key", environment => { environment.SMARTCUT_LICENSE_PUBLIC_MODULUS_HEX = "0123"; }]
  ];
  for (const [name, breakConfiguration] of cases) {
    await t.test(name, async () => {
      const environment = env(expected);
      breakConfiguration(environment);
      let fetchCount = 0;
      const handler = testHandler(expected,
        { fetchImpl: async () => { ++fetchCount; throw new Error("unexpected_fetch"); } });
      const result = await handler.fetch(new Request("https://licensing.example/ready"), environment);
      assert.equal(result.status, 503);
      const text = await result.text();
      const body = JSON.parse(text);
      assert.equal(body.code, "service_not_ready");
      assert.equal(body.ready, false);
      assert.equal(fetchCount, 0);
      assert.equal(environment.LICENSE_STATE.getCount, 0);
      assert.equal(environment.LICENSE_STATE.putCount, 0);
      assert.equal(text.includes(expected.publicModulusHex), false);
      assert.equal(text.includes(wrong.privatePem.slice(64, 96)), false);
    });
  }
});

test("a valid but wrong signing key cannot consume a Lemon activation", async () => {
  const expected = await keys(); const wrong = await keys();
  const environment = env(expected);
  environment.SMARTCUT_PRIVATE_KEY_PEM = wrong.privatePem;
  const lemon = lemonFetch(); const handler = testHandler(expected, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "service_not_configured");
  assert.equal(lemon.calls.length, 0);
  assert.equal(environment.LICENSE_STATE.getCount, 0);
  assert.equal(environment.LICENSE_STATE.putCount, 0);
});

test("the production product stays pinned to the public key shipped in SmartCut64", async () => {
  const internallyMatchingButUntrusted = await keys();
  const environment = env(internallyMatchingButUntrusted);
  environment.LEMON_PRODUCT_ID = "1304562";
  const lemon = lemonFetch(); const handler = createHandler({ fetchImpl: lemon.fetchImpl });

  const readyResult = await handler.fetch(new Request("https://licensing.example/ready"), environment);
  assert.equal(readyResult.status, 503);
  assert.equal((await readyResult.json()).code, "service_not_ready");

  const activationResult = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(activationResult.status, 503);
  assert.equal((await activationResult.json()).code, "service_not_configured");
  assert.equal(lemon.calls.length, 0);
  assert.equal(environment.LICENSE_STATE.getCount, 0);
  assert.equal(environment.LICENSE_STATE.putCount, 0);
});

test("an unknown Lemon product has no signing trust anchor", async () => {
  const signing = await keys(); const environment = env(signing);
  environment.LEMON_PRODUCT_ID = "13045620";
  const handler = createHandler();
  const result = await handler.fetch(new Request("https://licensing.example/ready"), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "service_not_ready");
});

test("readiness pins the complete Lemon deployment tuple", async t => {
  const signing = await keys();
  const cases = [
    ["wrong API host", environment => {
      environment.LEMON_LICENSE_API_BASE = "https://licences.invalid/v1/licenses";
    }],
    ["wrong store", environment => { environment.LEMON_STORE_ID = "11"; }],
    ["wrong variants", environment => { environment.LEMON_VARIANT_IDS = "30,32"; }]
  ];
  for (const [name, change] of cases) {
    await t.test(name, async () => {
      const environment = env(signing);
      change(environment);
      let fetchCount = 0;
      const handler = testHandler(signing,
        { fetchImpl: async () => { ++fetchCount; throw new Error("unexpected_fetch"); } });
      const ready = await handler.fetch(new Request("https://licensing.example/ready"), environment);
      assert.equal(ready.status, 503);
      assert.equal((await ready.json()).code, "service_not_ready");
      const activation = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
        email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
      assert.equal(activation.status, 503);
      assert.equal((await activation.json()).code, "service_not_configured");
      assert.equal(fetchCount, 0);
      assert.equal(environment.LICENSE_STATE.getCount, 0);
      assert.equal(environment.LICENSE_STATE.putCount, 0);
    });
  }
});

test("a cached signing key cannot hide later API-host drift", async () => {
  const signing = await keys(); const environment = env(signing);
  const handler = testHandler(signing);
  assert.equal((await handler.fetch(new Request("https://licensing.example/ready"), environment)).status, 200);
  environment.LEMON_LICENSE_API_BASE = "https://licences.invalid/v1/licenses";
  const result = await handler.fetch(new Request("https://licensing.example/ready"), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "service_not_ready");
});

test("invalid UTF-8 webhooks are rejected as client input, not oversized payloads", async () => {
  const signing = await keys(); const environment = env(signing);
  const handler = testHandler(signing);
  const request = new Request("https://licensing.example/v1/webhooks/lemon", {
    method: "POST", headers: { "x-signature": "0".repeat(64) }, body: new Uint8Array([0xc3, 0x28])
  });
  const result = await handler.fetch(request, environment);
  assert.equal(result.status, 400);
  assert.equal((await result.json()).code, "invalid_encoding");
});

test("rejects another product before consuming an activation", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch({ productId: 999 });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "wrong-product-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 403);
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate"]);
});

test("a licence-state read failure returns a controlled error before Lemon", async () => {
  const signing = await keys(); const environment = env(signing);
  // The first read proves the namespace marker; fail the activation-record read.
  environment.LICENSE_STATE.failGetAt = 2;
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "activation_unavailable");
  assert.equal(lemon.calls.length, 0);
});

test("a lost Lemon activation response never returns an uncommitted entitlement", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch();
  const fetchImpl = async (url, options) => {
    if (new URL(url).pathname.endsWith("/activate")) {
      await lemon.fetchImpl(url, options);
      throw new Error("test_lost_activation_response");
    }
    return lemon.fetchImpl(url, options);
  };
  const handler = testHandler(signing, { fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 503);
  const body = await result.json();
  assert.equal(body.code, "upstream_unavailable");
  assert.equal(body.entitlement, undefined);
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate", "activate"]);
  const recordKey = [...environment.LICENSE_STATE.values.keys()]
    .find(key => key.startsWith("activation:"));
  assert.ok(recordKey);
  const pendingRecord = JSON.parse(environment.LICENSE_STATE.values.get(recordKey));
  assert.equal(pendingRecord.status, "revoked");
  assert.equal(pendingRecord.recovery_status, "activation_pending");
  assert.equal(deployedV1ActivationRoute(pendingRecord), "block");

  const retry = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(retry.status, 503);
  assert.equal((await retry.json()).code, "activation_recovery_pending");
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate", "activate"]);
});

test("a pre-activation state outage cannot consume a Lemon activation", async () => {
  const signing = await keys(); const environment = env(signing);
  environment.LICENSE_STATE.failAllPuts = true;
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "activation_commit_failed");
  assert.deepEqual(lemon.calls.map(call => call.operation), ["validate"]);
  assert.equal([...environment.LICENSE_STATE.values.keys()]
    .some(key => key.startsWith("activation:")), false);
});

test("releases a Lemon activation when licence-state persistence fails", async () => {
  const signing = await keys();
  for (const failPutAt of [2, 3, 4]) {
    const environment = env(signing);
    environment.LICENSE_STATE.failPutAt = failPutAt;
    const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
    const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
      email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
    assert.equal(result.status, 503);
    assert.equal((await result.json()).code, "activation_commit_failed");
    assert.deepEqual(lemon.calls.map(call => call.operation), ["validate", "activate", "deactivate"]);
    assert.equal(lemon.calls.at(-1).fields.instance_id, "00000000-0000-4000-8000-000000000001");
    const recordKey = [...environment.LICENSE_STATE.values.keys()]
      .find(key => key.startsWith("activation:"));
    assert.ok(recordKey);
    assert.equal(JSON.parse(environment.LICENSE_STATE.values.get(recordKey)).status, "deactivated");
  }
});

test("a mismatched rollback response cannot be treated as confirmed cleanup", async () => {
  const signing = await keys(); const environment = env(signing);
  environment.LICENSE_STATE.failPutAt = 2;
  const lemon = lemonFetch({ control: { deactivationLicenseId: 999 } });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", { license_key: "test-license-key",
    email: "buyer@example.com", installation_id: "0123456789abcdef0123456789abcdef" }), environment);
  assert.equal(result.status, 503);
  assert.equal((await result.json()).code, "activation_recovery_pending");
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "deactivate"]);
  const recordKey = [...environment.LICENSE_STATE.values.keys()]
    .find(key => key.startsWith("activation:"));
  assert.ok(recordKey);
  const rollbackRecord = JSON.parse(environment.LICENSE_STATE.values.get(recordKey));
  assert.equal(rollbackRecord.status, "revoked");
  assert.equal(rollbackRecord.recovery_status, "rollback_pending");
  assert.equal(deployedV1ActivationRoute(rollbackRecord), "block");
});

test("records and reconciles a failed Lemon rollback before activating again", async t => {
  const signing = await keys();
  for (const failureMode of ["rejected", "network", "lost success response", "invalid but present"]) {
    await t.test(failureMode, async () => {
      const environment = env(signing);
      environment.LICENSE_STATE.failPutAt = 2;
      const control = failureMode === "rejected"
        ? { deactivated: false }
        : { throwOnDeactivate: true };
      const lemon = lemonFetch({ control });
      const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
      const body = { license_key: "test-license-key", email: "buyer@example.com",
        installation_id: "0123456789abcdef0123456789abcdef" };

      const first = await handler.fetch(post("/v1/activate", body), environment);
      assert.equal(first.status, 503);
      assert.equal((await first.json()).code, "activation_recovery_pending");
      const recordKey = [...environment.LICENSE_STATE.values.keys()]
        .find(key => key.startsWith("activation:"));
      assert.ok(recordKey);
      const rollbackRecord = JSON.parse(environment.LICENSE_STATE.values.get(recordKey));
      assert.equal(rollbackRecord.status, "revoked");
      assert.equal(rollbackRecord.recovery_status, "rollback_pending");
      assert.equal(deployedV1ActivationRoute(rollbackRecord), "block");
      assert.deepEqual(lemon.calls.map(call => call.operation),
        ["validate", "activate", "deactivate"]);

      control.deactivated = true;
      control.throwOnDeactivate = false;
      if (failureMode === "lost success response") control.notFoundForInstance = true;
      if (failureMode === "invalid but present") control.validateExistingFalse = true;
      const retry = await handler.fetch(post("/v1/activate", body), environment);
      assert.equal(retry.status, 200);
      const expectedCalls = failureMode === "lost success response"
        ? ["validate", "activate", "deactivate", "validate", "validate", "activate"]
        : ["validate", "activate", "deactivate", "validate", "deactivate", "validate", "activate"];
      assert.deepEqual(lemon.calls.map(call => call.operation), expectedCalls);
      assert.equal(JSON.parse(environment.LICENSE_STATE.values.get(recordKey)).status, "active");
    });
  }
});

test("a failed rollback plus sustained KV outage never returns an entitlement", async () => {
  const signing = await keys(); const environment = env(signing);
  // The durable intent succeeds; every write after Lemon is unavailable.
  environment.LICENSE_STATE.failPutsFrom = 2;
  const lemon = lemonFetch({ control: { deactivated: false } });
  const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const result = await handler.fetch(post("/v1/activate", {
    license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef"
  }), environment);
  assert.equal(result.status, 503);
  const responseBody = await result.json();
  assert.equal(responseBody.code, "activation_recovery_pending");
  assert.equal(responseBody.entitlement, undefined);
  assert.deepEqual(lemon.calls.map(call => call.operation),
    ["validate", "activate", "deactivate"]);
  const recordKey = [...environment.LICENSE_STATE.values.keys()]
    .find(key => key.startsWith("activation:"));
  assert.ok(recordKey);
  const pendingRecord = JSON.parse(environment.LICENSE_STATE.values.get(recordKey));
  assert.equal(pendingRecord.status, "revoked");
  assert.equal(pendingRecord.recovery_status, "activation_pending");
  assert.equal(deployedV1ActivationRoute(pendingRecord), "block");

  const retry = await handler.fetch(post("/v1/activate", {
    license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef"
  }), environment);
  assert.equal(retry.status, 503);
  assert.equal((await retry.json()).code, "activation_recovery_pending");
  assert.equal(lemon.calls.filter(call => call.operation === "activate").length, 1);
});

test("deactivates only the recorded machine instance", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  await handler.fetch(post("/v1/activate", body), environment);
  assert.equal((await handler.fetch(post("/v1/deactivate", body), environment)).status, 200);
  assert.equal(lemon.calls.at(-1).operation, "deactivate");
  assert.equal(lemon.calls.at(-1).fields.instance_id, "00000000-0000-4000-8000-000000000001");
});

test("accepts signed refund event names, including Lemon simulation payloads", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  await handler.fetch(post("/v1/activate", body), environment);
  const payload = { meta: { event_name: "order_refunded" },
    data: { id: "40", attributes: { status: "paid", refunded: false } } };
  assert.equal((await handler.fetch(post("/v1/webhooks/lemon", payload,
    { "x-signature": "0".repeat(64) }), environment)).status, 401);
  assert.equal((await handler.fetch(await signedWebhook(environment.LEMON_WEBHOOK_SECRET, payload),
    environment)).status, 200);
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 403);
});

test("revokes an activated installation when Lemon disables its licence", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const body = { license_key: "test-license-key", email: "buyer@example.com",
    installation_id: "0123456789abcdef0123456789abcdef" };
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  const payload = { meta: { event_name: "license_key_updated" },
    data: { id: "60", attributes: { disabled: true, status: "disabled" } } };
  assert.equal((await handler.fetch(await signedWebhook(environment.LEMON_WEBHOOK_SECRET, payload),
    environment)).status, 200);
  assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 403);
});

test("refund revocation covers every activation instead of retaining only the last 100", async () => {
  const signing = await keys(); const environment = env(signing);
  const lemon = lemonFetch(); const handler = testHandler(signing, { fetchImpl: lemon.fetchImpl });
  const bodies = [];
  for (let index = 0; index < 105; ++index) {
    const installation_id = index.toString(16).padStart(32, "0");
    const body = { license_key: "test-license-key", email: "buyer@example.com", installation_id };
    bodies.push(body);
    assert.equal((await handler.fetch(post("/v1/activate", body), environment)).status, 200);
  }
  const payload = { meta: { event_name: "order_refunded" },
    data: { id: "40", attributes: { status: "refunded" } } };
  assert.equal((await handler.fetch(await signedWebhook(environment.LEMON_WEBHOOK_SECRET, payload),
    environment)).status, 200);
  for (const index of [0, 50, 104])
    assert.equal((await handler.fetch(post("/v1/activate", bodies[index]), environment)).status, 403);
});
