/**
 * Copyright © 2024 Nevis Security AG. All rights reserved.
 */

import type { PasswordEnrollmentError } from '../../error/password/enrollment/PasswordEnrollmentError';
import { PasswordEnrollmentErrorConverter } from '../../error/password/enrollment/PasswordEnrollmentErrorConverter';

/**
 * The object providing some contextual information during password enrollment.
 *
 * @see {@link PasswordEnroller.enrollPassword}
 */
export abstract class PasswordEnrollmentContext {
	/**
	 * The username associated with the authenticator.
	 */
	abstract username: string;

	/**
	 * When a recoverable error occurred during the last password enrollment, this method returns the
	 * object describing the last error.
	 */
	abstract lastRecoverableError?: PasswordEnrollmentError;

	/**
	 * Alternate constructor that creates an instance from a json.
	 *
	 * @param json contains the source for instance creation.
	 * @returns the created instance.
	 */
	static fromJson(json: any): PasswordEnrollmentContext {
		return PasswordEnrollmentContextImpl.fromJson(json);
	}
}

class PasswordEnrollmentContextImpl extends PasswordEnrollmentContext {
	username: string;
	lastRecoverableError?: PasswordEnrollmentError;

	private constructor(username: string, lastRecoverableError?: PasswordEnrollmentError) {
		super();
		this.username = username;
		this.lastRecoverableError = lastRecoverableError;
	}

	static fromJson(json: any) {
		const username = json.username;
		const lastRecoverableError =
			json.lastRecoverableError &&
			new PasswordEnrollmentErrorConverter(json.lastRecoverableError).convert();
		return new PasswordEnrollmentContextImpl(username, lastRecoverableError);
	}
}
