import type { Error as ErrorProto } from "@cerbos/api/cerbos/cloud/epdp/v2/epdp_pb";
import type { Code } from "@cerbos/api/google/rpc/code_pb";

export class ServerError extends Error {
  public readonly code: Code;

  public static from({ code, message }: ErrorProto): ServerError {
    return new ServerError(code, message);
  }

  public constructor(
    code: Code,
    message: string,
    options?: { cause?: unknown },
  ) {
    super(message, options);
    this.code = code;
    this.name = this.constructor.name;

    // `Error.captureStackTrace` is not available in all browsers
    if ("captureStackTrace" in Error) {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}
