import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";

const root = fileURLToPath(new URL("../../../", import.meta.url));
const source = (relative: string) => readFileSync(`${root}/${relative}`, "utf8");

describe("ADR-0009 deployment trust boundary", () => {
  it("keeps PostgreSQL and the privileged control plane behind loopback HTTPS ingress", () => {
    const deploy = source("infra/dogfood/deploy-debian3.sh");
    expect(deploy).toContain("AWP_CONTROL_HOST=127.0.0.1");
    expect(deploy).toContain("AWP_WEB_HOST=127.0.0.1");
    expect(deploy).toContain("AWP_EXECUTION_CALLBACK_BASE_URL=https://$TAILSCALE_DNS_NAME/api");
    expect(deploy).toContain('tailscale serve --bg --yes --https=443 "http://127.0.0.1:$WEB_PORT"');
    expect(deploy).toContain("AWP_OPERATOR_PASSWORD_HASH=$OPERATOR_PASSWORD_HASH");
    expect(deploy).toContain("operator-password-hash");

    const webEnvironment = deploy.match(
      /cat > "\$CONFIG_DIR\/web\.env" <<EOF\n([\s\S]*?)\nEOF/u,
    )?.[1];
    expect(webEnvironment).toBeDefined();
    expect(webEnvironment).not.toMatch(/DATABASE_URL|POSTGRES|OPERATOR_PASSWORD_HASH/u);
  });

  it("keeps the public web process database-free and never trusts a caller-supplied session header", () => {
    const webPackage = JSON.parse(source("apps/web/package.json")) as {
      dependencies?: Record<string, string>;
    };
    expect(Object.keys(webPackage.dependencies ?? {})).not.toContain("@awp/persistence");
    expect(Object.keys(webPackage.dependencies ?? {})).not.toContain("postgres");

    const webServer = source("apps/web/src/server.ts");
    expect(webServer).not.toMatch(/request\.headers\[["']x-awp-session["']\]/u);
    expect(webServer).toContain("internalSessionHeaders(token");
    expect(webServer).toContain('"/api/internal/execution/complete"');
    expect(webServer).toContain('"/api/internal/execution/fail"');
    expect(webServer).toContain('"/api/internal/execution/review"');
  });

  it("defaults the control-plane HTTP listener to loopback", () => {
    const server = source("apps/control-plane/src/server.ts");
    expect(server).toContain('const host = input.host ?? "127.0.0.1"');
    expect(server).toContain("serve({ fetch: app.fetch, port, hostname: host })");
  });

  it("does not enable the post-commit crash hook in dogfood deployment configuration", () => {
    const deploy = source("infra/dogfood/deploy-debian3.sh");
    expect(deploy).not.toContain("AWP_CRASH_AFTER_STEP_COMMIT");
  });
});
