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

import NevisMobileAuthentication

final class PasswordEnrollerImpl: Sendable {
	// MARK: Properties

	let operationId: String

	// MARK: Initialization

	init(operationId: String) {
		self.operationId = operationId
	}
}

// MARK: - PasswordEnroller

extension PasswordEnrollerImpl: PasswordEnroller {
	func enrollPassword(context: PasswordEnrollmentContext, handler: PasswordEnrollmentHandler) {
		Task {
			let operation: any UserInteractionOperation = await OperationCache.shared.read(by: operationId)
			let authenticator = await operation.findAuthenticator(aaid: AuthenticatorAaid.Password)
			let state = PasswordEnrollState(context: context,
			                                handler: handler,
			                                authenticator: authenticator)
			await OperationCache.shared.update(by: operationId,
			                                   operation: operation.update(state: state))

			let message = PasswordEnrollerMessage(operationId: operationId,
			                                      context: context)
			EventEmitter.shared.dispatch(event: .passwordEnroll, message: message)
		}
	}

	func passwordPolicy() -> PasswordPolicy {
		PasswordPolicyImpl(operationId: operationId)
	}
}
