/**
 * Server-authoritative lookup for the things an office pack *authored* — screen
 * surfaces today, device hardware as well now.
 *
 * The rule both callers share: a client says "this screen", "this microphone",
 * and the server checks the claim against a pack it resolved itself rather than
 * against anything in the request. `officeHasMediaBinding` does it for a screen
 * share; `server/src/devices/store.ts` does it for a device command, and reads
 * the same bundled packs through `bundledOffice` for the same reason.
 */

import { Plan } from "../../../src/interiors/plan.ts";
import type { Office } from "../../../src/interiors/types.ts";
import FRONTIER_VALLEY from "../../../src/offices/frontier-valley.ts";
import LUMBRIDGE_HQ from "../../../src/offices/lumbridge-hq.ts";
import MATEO_COURT from "../../../src/offices/mateo-court.ts";
import type { ScreenShareBinding } from "../../../src/media/signalingTypes.ts";

const SCREEN_KINDS = new Set([
  "tera:screen.monitor",
  "tera:screen.wall-display",
]);

const BUNDLED_OFFICES: ReadonlyMap<string, Office> = new Map(
  [LUMBRIDGE_HQ, FRONTIER_VALLEY, MATEO_COURT].map((office) => [office.id, office]),
);

/**
 * The three packs this repo ships, by id, or `null` for anything else.
 *
 * A bundled pack is public sample geometry — it is compiled into the browser
 * bundle, so its authored catalogue of screens and devices is already public by
 * construction and the server reading its own copy tells nobody anything new.
 * That is what makes it a safe exception, and it is the **only** exception: no
 * real or private pack is ever inferred from anything, and an id that is not one
 * of these three is not an office as far as this function is concerned.
 *
 * Why it is needed at all: the browser renders bundled packs without asking the
 * API for them, so a viewer can be standing in `lumbridge-hq` on a deployment
 * that has no `TERA_OFFICES_DIR` at all. Without this, every server-side check
 * about the room they are in would have nothing to check against.
 */
export function bundledOffice(officeId: string): Office | null {
  return BUNDLED_OFFICES.get(officeId) ?? null;
}

/**
 * Confirm an exact client binding against a validated/resolved office pack.
 * Room membership is computed from the prop's authored position rather than
 * trusting a caller-provided label.
 */
export function officeHasMediaBinding(office: Office, binding: ScreenShareBinding): boolean {
  if (office.id !== binding.officeId) return false;
  const plan = new Plan(office, { depth: "full", warn: false });
  const level = plan.level(binding.levelId);
  if (!level) return false;
  const prop = level.props.find((candidate) => candidate.id === binding.screenId);
  if (!prop || !SCREEN_KINDS.has(prop.kind)) return false;
  const roomId = plan.roomAt(level.id, prop.position)?.id ?? null;
  return roomId === binding.roomId;
}
