import { afterAll, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { getAuthzCatalog, hasAuthzCatalog } from "@wrnexus/authz";
import { startServer } from "../src/index.ts";

// Fixtures live inside the repo tree, not os.tmpdir(): a scaffolded file under
// app/authz importing "@wrnexus/authz" by bare specifier resolves via the root
// tsconfig.json `paths` map, walked from the *imported file's* location — an
// out-of-tree path (os.tmpdir(), often a different drive on Windows) never
// reaches it.
const scratchRoot = join(import.meta.dir, ".tmp-authz-startserver");
mkdirSync(scratchRoot, { recursive: true });

function scaffold(name: string, authzFiles: Record<string, string>): string {
  const root = mkdtempSync(join(scratchRoot, `${name}-`));
  const appDir = join(root, "app");
  mkdirSync(join(appDir, "pages"), { recursive: true });
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({ name: `authz-startserver-${name}` }),
    "utf8",
  );
  if (Object.keys(authzFiles).length) {
    mkdirSync(join(appDir, "authz"), { recursive: true });
    for (const [file, body] of Object.entries(authzFiles)) {
      writeFileSync(join(appDir, "authz", file), body, "utf8");
    }
  }
  return appDir;
}

afterAll(() => {
  rmSync(scratchRoot, { recursive: true, force: true });
});

async function waitFor(
  condition: () => boolean,
  timeoutMs: number,
  intervalMs = 50,
): Promise<void> {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    if (condition()) return;
    await new Promise((resolve) => setTimeout(resolve, intervalMs));
  }
  if (!condition()) throw new Error(`waitFor: condition was not met within ${timeoutMs}ms`);
}

describe("dev boot loads the authz catalog before middleware is resolved", () => {
  test("an app with declarations makes getAuthzCatalog() return them after boot", async () => {
    const appDir = scaffold("has-decls", {
      "main.ts": `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:read": { title: "View posts" } } });`,
    });
    const server = await startServer({
      appDir,
      hostname: "127.0.0.1",
      port: 0,
      mode: "development",
      hmr: false,
    });
    try {
      expect(hasAuthzCatalog()).toBe(true);
      expect(getAuthzCatalog().permissions.has("post:read")).toBe(true);
      const cacheDir = join(appDir, "..", `.wrnexus-${process.pid}`);
      mkdirSync(cacheDir, { recursive: true });
      writeFileSync(join(cacheDir, "generated.js"), "generated", "utf8");
      expect(existsSync(cacheDir)).toBe(true);
    } finally {
      server.stop();
    }
    expect(existsSync(join(appDir, "..", `.wrnexus-${process.pid}`))).toBe(false);
  });

  test("an app with no app/authz declarations boots without throwing", async () => {
    const appDir = scaffold("no-decls", {});
    const server = await startServer({
      appDir,
      hostname: "127.0.0.1",
      port: 0,
      mode: "development",
      hmr: false,
    });
    try {
      expect(getAuthzCatalog().permissions.size).toBe(0);
    } finally {
      server.stop();
    }
  });

  test("a conflicting pair of declarations fails the boot, naming both source files", async () => {
    const appDir = scaffold("conflict", {
      "a.ts": `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:read": { risk: "low" } } });`,
      "b.ts": `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:read": { risk: "high" } } });`,
    });

    let thrown: unknown;
    try {
      const server = await startServer({
        appDir,
        hostname: "127.0.0.1",
        port: 0,
        mode: "development",
        hmr: false,
      });
      // Should be unreachable; stop it anyway so a regression doesn't leak a port.
      server.stop();
    } catch (error) {
      thrown = error;
    }

    expect(thrown).toBeInstanceOf(Error);
    const message = (thrown as Error).message;
    expect(message).toContain("WRN-AUTHZ-CONFLICT");
    expect(message).toContain(join(appDir, "authz", "a.ts"));
    expect(message).toContain(join(appDir, "authz", "b.ts"));
  });

  test("editing a declaration in a RUNNING dev server updates the live catalog, via the real file watcher", async () => {
    const appDir = scaffold("hmr-live", {
      "main.ts": `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:read": {} } });`,
    });
    const server = await startServer({
      appDir,
      hostname: "127.0.0.1",
      port: 0,
      mode: "development",
      hmr: true,
    });
    try {
      expect(getAuthzCatalog().permissions.has("post:read")).toBe(true);
      expect(getAuthzCatalog().permissions.has("post:write")).toBe(false);

      // A real write to disk, picked up by the real fs watcher (watch.ts /
      // startWatcher) — not a direct call into any internal hot-update
      // function. This is the only way to prove the wiring actually works,
      // as opposed to proving only that the code branch exists.
      writeFileSync(
        join(appDir, "authz", "main.ts"),
        `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:write": {} } });`,
        "utf8",
      );

      await waitFor(() => getAuthzCatalog().permissions.has("post:write"), 10_000);

      expect(getAuthzCatalog().permissions.has("post:write")).toBe(true);
      expect(getAuthzCatalog().permissions.has("post:read")).toBe(false);
    } finally {
      server.stop();
    }
  }, 15_000);
});
