import type { Auth0Error } from 'auth0-js';

export class WidgetError extends Error {
	cause?: unknown;
	code?: string;
	error?: Error | Auth0Error['error'];
	errorDescription?: string;
	message: string;
	statusCode?: number;
	statusText?: string;

	constructor(options?: WidgetErrorOptions) {
		super();

		const {
			code,
			description,
			error,
			errorDescription,
			error_description,
			cause,
			message,
			original,
			statusCode,
			statusText,
		} = options || {};

		this.cause = cause;
		this.code = code ?? statusCode?.toString();
		this.errorDescription =
			errorDescription ?? error_description ?? description;
		this.message = message ?? this.errorDescription ?? 'Unknown error';
		this.statusCode = statusCode;
		this.statusText = statusText;

		if (original && !(error instanceof Error)) {
			this.error = new Error(
				this?.errorDescription ?? this?.statusText ?? this.message
			);
		}

		if (error instanceof Error) {
			this.error = error;
			this.message = error?.message;
		}
	}
}

interface WidgetErrorOptions extends ErrorOptions, Omit<Auth0Error, 'error'> {
	error?: Error | Auth0Error['error'];
	message?: string;
}
