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

import NevisMobileAuthentication

protocol PasswordChangeOperationState: OperationState { /* . */ }

// MARK: -

actor PasswordChangeState: PasswordChangeOperationState {
	// MARK: Properties

	let context: PasswordChangeContext
	let handler: PasswordChangeHandler

	// MARK: Initialization

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

	// MARK: Public Interface

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

	// MARK: OperationState

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

// MARK: -

actor PasswordValidateForPasswordChangeState: PasswordChangeOperationState {
	// MARK: Properties

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

	// MARK: Initialization

	init(onSuccess: @escaping @Sendable () -> (), onValidationError: @escaping @Sendable (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))
	}
}
