/**
 * `GET /api/v1/offices/:id`.
 *
 * The one authenticated route, and the one place the 404 rule matters: an office
 * the caller may not see answers **404, not 403**, and answers it identically to
 * an office that does not exist. A 403 is an existence oracle — walk the id space
 * and the status code tells you every tenant on the box. CONTRACT.md §6.
 *
 * The same reasoning is why the not-found path does no work first: resolve the
 * viewer, load the doc, and take one exit.
 */

import type { FastifyInstance } from "fastify";
import { publicCache } from "../cache.ts";
import type { ErrorBody } from "../../../src/server/wire.ts";
import type { Services } from "../services.ts";

const NOT_FOUND: ErrorBody = { error: "not_found", message: "No such office." };

export function registerOffices(app: FastifyInstance, services: Services): void {
  app.get<{ Params: { id: string } }>("/api/v1/offices/:id", async (req, reply) => {
    const doc = await services.offices.get(req.params.id);
    if (doc === null) return reply.code(404).send(NOT_FOUND);

    if (doc.visibility === "private") {
      const viewer = await services.auth.resolve(req);
      if (!viewer.authenticated) return reply.code(404).send(NOT_FOUND);
    }

    // Only a public office may be cached by anything shared. An unlisted one is
    // reachable by anybody holding the id, but it should not accumulate in a CDN
    // where the id is no longer needed to find it.
    if (doc.visibility === "public") publicCache(req, reply, services.config.publicMaxAge);

    return doc;
  });
}
