import { forbidden, unauthorized } from "./errors.mjs";

const DEMO_PRINCIPALS = Object.freeze({
  "fde-demo-token": Object.freeze({
    subject: "fde-learner",
    tenantId: "aster-health",
    permissions: Object.freeze(["case:read", "recommendation:write", "operation:read"]),
  }),
  "observer-demo-token": Object.freeze({
    subject: "service-observer",
    tenantId: "aster-health",
    permissions: Object.freeze(["telemetry:read"]),
  }),
  "lab-admin-demo-token": Object.freeze({
    subject: "lab-failure-injector",
    tenantId: "aster-health",
    permissions: Object.freeze([
      "case:read",
      "recommendation:write",
      "operation:read",
      "telemetry:read",
      "failure:inject",
    ]),
  }),
});

export function resolveBearer(authorizationHeader) {
  const match = /^Bearer\s+(.+)$/i.exec(authorizationHeader ?? "");
  const principal = match ? DEMO_PRINCIPALS[match[1]] : undefined;
  if (!principal) {
    throw unauthorized();
  }
  return principal;
}

export function requirePermission(principal, permission) {
  if (!principal?.permissions?.includes(permission)) {
    throw forbidden(`Permission ${permission} is required.`);
  }
}

export const demoTokenNames = Object.freeze(Object.keys(DEMO_PRINCIPALS));
