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

import NevisMobileAuthentication

final class PinEnrollerImpl: Sendable {
	// MARK: Properties

	let operationId: String
	let policy: PinPolicy?

	// MARK: Initialization

	init(operationId: String, pinPolicy: PinPolicy?) {
		self.operationId = operationId
		self.policy = pinPolicy
	}
}

// MARK: - PinEnroller

extension PinEnrollerImpl: PinEnroller {
	func enrollPin(context: PinEnrollmentContext, handler: PinEnrollmentHandler) {
		Task {
			let operation: any UserInteractionOperation = await OperationCache.shared.read(by: operationId)
			let authenticator = await operation.findAuthenticator(aaid: AuthenticatorAaid.Pin)
			let state = PinEnrollState(context: context,
			                           handler: handler,
			                           authenticator: authenticator)
			await OperationCache.shared.update(by: operationId,
			                                   operation: operation.update(state: state))

			let message = PinEnrollerMessage(operationId: operationId,
			                                 context: context)
			EventEmitter.shared.dispatch(event: .pinEnroll, message: message)
		}
	}

	func pinPolicy() -> PinPolicy {
		policy ?? PinPolicyImpl(operationId: operationId)
	}
}
