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

import NevisMobileAuthentication

class PasswordChangeOperationState: OperationState {
	// MARK: OperationState Overrides

	func cancel() {
		fatalError("Must override.")
	}
}

// MARK: -

class PasswordChangeState: PasswordChangeOperationState {
	// MARK: Properties

	let context: PasswordChangeContext?
	let handler: PasswordChangeHandler?

	// MARK: Initialization

	init(context: PasswordChangeContext?, handler: PasswordChangeHandler? = nil) {
		self.context = context
		self.handler = handler
	}

	// MARK: Public Interface

	func change(password: String, newPassword: String) {
		handler?.passwords(password, newPassword)
	}

	// MARK: OperationState Overrides

	override func cancel() {
		handler?.cancel()
	}
}

// MARK: -

class PasswordValidateForPasswordChangeState: PasswordChangeOperationState {
	// MARK: Properties

	let onSuccess: () -> ()
	let onValidationError: (PasswordChangeValidationError) -> ()

	// MARK: Initialization

	init(onSuccess: @escaping () -> (), onValidationError: @escaping (PasswordChangeValidationError) -> ()) {
		self.onSuccess = onSuccess
		self.onValidationError = onValidationError
	}

	// MARK: Public Interface

	func validatePassword(errorMessage: String?, cause: String?) {
		guard let errorMessage else {
			return onSuccess()
		}

		var error: Error? {
			guard let cause else {
				return nil
			}
			return PasswordValidationError.InvalidPassword(cause: cause)
		}
		onValidationError(.InvalidPassword(message: errorMessage, cause: error))
	}
}
