import { describe, expect, test } from "bun:test";
import { defineService, implement, procedure } from "@wrnexus/rpc";
import { v } from "@wrnexus/validation";
import { handleRpcRequest, isInternalCaller, isRpcPath } from "../src/rpc-dispatch.ts";
import { createProductionHandlers, type ProdManifest } from "../src/prod.ts";

const demo = defineService({
  name: "demo",
  procedures: {
    add: procedure
      .input(v.object({ a: v.number() }))
      .output<{ a: number }>()
      .build(),
  },
});
const services = new Map([
  ["demo", implement(demo, { add: async ({ a }) => ({ a }) }, { selfApp: "demo-app" })],
]);

function request(path: string, headers: Record<string, string> = {}) {
  return new Request(`http://demo.test${path}`, {
    method: "POST",
    headers: { "content-type": "application/json", ...headers },
    body: JSON.stringify({ a: 2 }),
  });
}

describe("RPC endpoint", () => {
  test("only matches its reserved prefix", () => {
    expect(isRpcPath("/__wrnexus/rpc/demo/add")).toBe(true);
    expect(isRpcPath("/__wrnexus/rpcx/demo/add")).toBe(false);
  });

  test("dispatches a private request", async () => {
    const req = request("/__wrnexus/rpc/demo/add", { "x-wrnexus-internal": "1" });
    expect(await (await handleRpcRequest(req, new URL(req.url), services))!.json()).toEqual({
      ok: true,
      value: { a: 2 },
    });
  });

  test("rejects public or forwarded requests", async () => {
    const external = request("/__wrnexus/rpc/demo/add");
    expect((await handleRpcRequest(external, new URL(external.url), services))!.status).toBe(404);
    const forwarded = request("/__wrnexus/rpc/demo/add", {
      "x-wrnexus-internal": "1",
      "x-forwarded-for": "203.0.113.1",
    });
    expect(isInternalCaller(forwarded)).toBe(false);
    expect((await handleRpcRequest(forwarded, new URL(forwarded.url), services))!.status).toBe(404);
  });

  describe("C1: prototype-chain procedure names cannot bypass the permission gate", () => {
    const PROTO_NAMES = [
      "constructor",
      "toString",
      "valueOf",
      "hasOwnProperty",
      "__proto__",
      "isPrototypeOf",
    ];

    for (const name of PROTO_NAMES) {
      test(`"${name}" in the URL path yields RPC_UNKNOWN`, async () => {
        const req = request(`/__wrnexus/rpc/demo/${name}`, { "x-wrnexus-internal": "1" });
        const res = await handleRpcRequest(req, new URL(req.url), services);
        expect(await res!.json()).toMatchObject({ ok: false, code: "RPC_UNKNOWN" });
      });
    }

    test(`"constructor" as the SERVICE segment also yields RPC_UNKNOWN`, async () => {
      const req = request("/__wrnexus/rpc/constructor/add", { "x-wrnexus-internal": "1" });
      const res = await handleRpcRequest(req, new URL(req.url), services);
      expect(await res!.json()).toMatchObject({ ok: false, code: "RPC_UNKNOWN" });
    });
  });

  test("production manifests load and dispatch service implementations", async () => {
    const manifest: ProdManifest = {
      pages: [],
      api: [],
      realtime: [],
      middleware: [],
      components: [],
      layouts: [],
      services: [{ name: "demo", mod: { default: services.get("demo") } }],
    };
    const handlers = createProductionHandlers(manifest, {});
    const req = request("/__wrnexus/rpc/demo/add", { "x-wrnexus-internal": "1" });
    const response = await handlers.fetch(req, {} as never);
    expect(await response!.json()).toEqual({ ok: true, value: { a: 2 } });
  });
});
