import { createHmac } from 'node:crypto';
import { getKey } from 'officerdb/secret-store';

const RELAY_TOKEN_CONTEXT = 'officer-browser-relay-v1';

// Nothing imports this file today — the browser relay is switched off pending extraction into a plugin
// (see server.tsx). Updated with everything else so it is coherent when it comes back: it read
// JWT_SECRET from the environment, which no longer exists, and would have thrown at module load.
//
// When it is extracted it should take its own purpose rather than borrowing 'jwt' — a plugin deriving
// tokens from the platform's signing key is the coupling the per-purpose split exists to remove.

export function deriveRelayToken(userId: number, port: number, salt: string): string {
  return createHmac('sha256', getKey('jwt')).update(`${RELAY_TOKEN_CONTEXT}:${port}:${userId}:${salt}`).digest('hex');
}

const tokenToUser = new Map<string, number>();

export function registerUserToken(userId: number, port: number, salt: string): string {
  const token = deriveRelayToken(userId, port, salt);
  tokenToUser.set(token, userId);
  return token;
}

export function unregisterUserToken(token: string): void {
  tokenToUser.delete(token);
}

export function restoreUserTokens(entries: Array<{ userId: number; salt: string }>, port: number): void {
  for (const { userId, salt } of entries) {
    const token = deriveRelayToken(userId, port, salt);
    tokenToUser.set(token, userId);
  }
}

export function resolveUserFromToken(token: string): number | null {
  return tokenToUser.get(token) ?? null;
}

export function getRelayAuthHeader(): string {
  return 'x-officer-relay-token';
}
