// Unit test for the /api/c/ company-context preHandler (Task 2 of
// docs/superpowers/plans/2026-07-31-local-app.md). No routes under /api/c/
// exist yet (those arrive in later tasks) — this exercises the mechanism
// directly against a minimal Fastify instance with a throwaway test route,
// no database needed.

import { describe, it, expect } from "vitest";
import Fastify from "fastify";
import { companyContextPlugin } from "../../server/src/companyContext.js";

async function buildTestApp() {
  const fastify = Fastify({ logger: false });
  // Called directly, not via fastify.register() — see the comment on
  // companyContextPlugin in server/src/companyContext.ts for why: register()
  // would encapsulate the hook away from these sibling routes.
  await companyContextPlugin(fastify);
  fastify.get("/api/c/ping", async (request) => ({ companyId: request.companyId }));
  fastify.get("/api/other", async () => ({ ok: true }));
  return fastify;
}

describe("companyContextPlugin (/api/c/ X-Company-Id enforcement)", () => {
  it("rejects a request under /api/c/ with no X-Company-Id header", async () => {
    const app = await buildTestApp();
    try {
      const res = await app.inject({ method: "GET", url: "/api/c/ping" });
      expect(res.statusCode).toBe(400);
    } finally {
      await app.close();
    }
  });

  it("rejects a non-uuid X-Company-Id header", async () => {
    const app = await buildTestApp();
    try {
      const res = await app.inject({
        method: "GET", url: "/api/c/ping", headers: { "x-company-id": "not-a-uuid" },
      });
      expect(res.statusCode).toBe(400);
    } finally {
      await app.close();
    }
  });

  it("accepts a valid uuid and exposes it as request.companyId", async () => {
    const app = await buildTestApp();
    try {
      const id = "3fa85f64-5717-4562-b3fc-2c963f66afa6";
      const res = await app.inject({
        method: "GET", url: "/api/c/ping", headers: { "x-company-id": id },
      });
      expect(res.statusCode).toBe(200);
      expect((res.json() as { companyId: string }).companyId).toBe(id);
    } finally {
      await app.close();
    }
  });

  it("does not require the header for routes outside /api/c/", async () => {
    const app = await buildTestApp();
    try {
      const res = await app.inject({ method: "GET", url: "/api/other" });
      expect(res.statusCode).toBe(200);
    } finally {
      await app.close();
    }
  });
});
