import { expect, test } from "bun:test";
import { createRpcHandler } from "../src/rpc.ts";

function request(args: unknown[]): Request {
  return new Request("http://localhost/__wrnexus/rpc", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ component: "Demo", function: "save", args }),
  });
}

const handler = createRpcHandler({
  resolve: async () => ({
    functions: { save: (value: string) => value.toUpperCase() },
    manifest: [
      {
        function: "save",
        parameters: [{ name: "value", type: "string", optional: false }],
        returnType: "string",
      },
    ],
  }),
});

test("validates RPC input and output contracts", async () => {
  const valid = await handler(request(["hello"]));
  expect(valid.status).toBe(200);
  expect(await valid.json()).toEqual(expect.objectContaining({ ok: true, value: "HELLO" }));

  const invalid = await handler(request([12]));
  expect(invalid.status).toBe(400);
  expect(((await invalid.json()) as any).error.code).toBe("WRN-RPC-INPUT");
});
