import assert from "node:assert/strict";
import test from "node:test";
import {
  PRODUCTION_RESOURCES,
  buildProductionConfig,
  resolveProductionInventory,
  wranglerInvocation,
} from "../../scripts/cloudflare-production-config.mjs";

const databaseId = "123e4567-e89b-42d3-a456-426614174000";

test("selects only the exact HearBooks inventory", () => {
  const inventory = resolveProductionInventory({
    d1Json: JSON.stringify([
      { name: "reader-1-db", uuid: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" },
      { name: PRODUCTION_RESOURCES.database, uuid: databaseId },
    ]),
    r2Text: "name: reader-1-storage\nname: hearbooks-reader-storage\n",
  });
  assert.deepEqual(inventory, { databaseId });
});

test("refuses missing or duplicate HearBooks resources", () => {
  assert.throws(
    () => resolveProductionInventory({ d1Json: "[]", r2Text: "" }),
    /exactly one hearbooks-reader-db/i,
  );
  assert.throws(
    () => resolveProductionInventory({
      d1Json: JSON.stringify([
        { name: PRODUCTION_RESOURCES.database, uuid: databaseId },
        { name: PRODUCTION_RESOURCES.database, uuid: "223e4567-e89b-42d3-a456-426614174000" },
      ]),
      r2Text: "name: hearbooks-reader-storage\n",
    }),
    /exactly one hearbooks-reader-db/i,
  );
  assert.throws(
    () => resolveProductionInventory({
      d1Json: JSON.stringify([{ name: PRODUCTION_RESOURCES.database, uuid: databaseId }]),
      r2Text: "name: reader-1-storage\n",
    }),
    /exactly one hearbooks-reader-storage/i,
  );
});

test("builds an isolated no-bundle Workers Static Assets config", () => {
  const config = buildProductionConfig({ databaseId });
  assert.equal(config.name, "hearbooks-reader");
  assert.equal(config.main, "./dist/server/index.js");
  assert.deepEqual(config.assets, { directory: "./dist/client" });
  assert.deepEqual(config.d1_databases, [{
    binding: "DB",
    database_name: "hearbooks-reader-db",
    database_id: databaseId,
    migrations_dir: "./drizzle",
  }]);
  assert.deepEqual(config.r2_buckets, [{ binding: "STORAGE", bucket_name: "hearbooks-reader-storage" }]);
  assert.equal(config.workers_dev, true);
  const serialized = JSON.stringify(config);
  assert.doesNotMatch(serialized, /reader-1|site-creator|chatgpt\.site|IMAGES/);
});

test("runs the local Wrangler JavaScript entry without a Windows cmd shim", () => {
  const invocation = wranglerInvocation({
    execPath: "C:\\Program Files\\nodejs\\node.exe",
    projectDirectory: "C:\\HearBooks\\site",
    arguments_: ["d1", "list", "--json"],
  });

  assert.equal(invocation.command, "C:\\Program Files\\nodejs\\node.exe");
  assert.deepEqual(invocation.arguments, [
    "C:\\HearBooks\\site\\node_modules\\wrangler\\bin\\wrangler.js",
    "d1",
    "list",
    "--json",
  ]);
});
