import type { CommandContext, QueryContext } from "./types";
import type { Result } from "./result";
import { InsufficientPermissionError } from "./errors";
import { ok, err } from "./result";

// Checks if any permission in the array matches the required key exactly
// or is a colon-delimited prefix (enabling hierarchical permissions).
function hasPermission(permissions: readonly string[], requiredKey: string): boolean {
  return permissions.some((p) => requiredKey === p || requiredKey.startsWith(p + ":"));
}

export function requirePermission(
  ctx: CommandContext | QueryContext,
  key: string,
): Result<void, InstanceType<typeof InsufficientPermissionError>> {
  if (!ctx.permissions || !hasPermission(ctx.permissions, key)) {
    return err(new InsufficientPermissionError(ctx.actorId, key));
  }
  return ok(undefined);
}
