import jwt from "jsonwebtoken";
import { Socket } from "socket.io";
import { asEntityId } from "@slackwsh/messaging";

/**
 * Simplification vs ARCHITECTURE §4.3's one-time WS ticket design: this MVP
 * verifies the same short-lived access JWT apps/api issues, rather than a
 * separate Redis-backed single-use ticket. Tenant scope is still fixed at
 * connect time and never re-read from client input after — the load-bearing
 * property §4.3 actually cares about — but the ticket-exchange hop (and its
 * defence against a leaked access token being replayed as a WS credential)
 * is deferred. Revisit before Phase 3 hardening.
 */
export function verifyAccessToken(socket: Socket): number {
  const token = socket.handshake.auth?.accessToken as string | undefined;
  if (!token) throw new Error("missing accessToken in socket auth");
  const secret = process.env.JWT_ACCESS_SECRET;
  if (!secret) throw new Error("JWT_ACCESS_SECRET is not set");
  const claims = jwt.verify(token, secret) as { sub: string | number };
  return asEntityId(claims.sub);
}
