/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */

export interface IError extends Error {
  response?: {
    status?: number;
    data?: {
      status?: string;
      message?: string;
    };
    config?: {
      data?: string;
    };
  };
}

export interface IPortalError {
  status: string;
  message?: string;
  statusCode?: number;
  requestPayload?: string;
}

export class PortalError extends Error implements IPortalError {
  private _name: string;
  private _status: string;
  private _message?: string;
  private _statusCode?: number;
  private _requestPayload?: string;

  constructor(status?: string, options: {message?: string; statusCode?: number; requestPayload?: string} = {}) {
    super(options.message || status);
    this._name = 'PortalError'; // Set the error name
    this._status = status || 'default'; // Custom status property
    this._message = options.message;
    this._statusCode = options.statusCode;
    this._requestPayload = options.requestPayload;
  }

  get status(): string {
    return this._status;
  }

  get name(): string {
    return this._name;
  }

  get message(): string | undefined {
    return this._message;
  }

  get statusCode(): number | undefined {
    return this._statusCode;
  }

  get requestPayload(): string | undefined {
    return this._requestPayload;
  }
}

export const transformToPortalError = (e: Error | IPortalError | string | unknown): PortalError => {
  if (e instanceof PortalError) {
    return e;
  }

  if (e instanceof Error) {
    return new PortalError('no-status-error', {message: e.message});
  }

  if (typeof e === 'string') {
    return new PortalError('no-status-error', {message: e});
  }

  return new PortalError();
};
