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

import NevisMobileAuthentication

struct TypedAuthenticator: Encodable {
	// MARK: Properties

	let wrapped: any Authenticator

	// MARK: Encodable

	enum CodingKeys: CodingKey {
		case aaid
		case registration
		case userEnrollment
		case isSupportedByHardware
		case isSupportedByOs
	}

	enum RegistrationCodingKeys: CodingKey {
		case registeredAccounts
	}

	enum AccountCodingKeys: String, CodingKey {
		case username
		case server
	}

	func encode(to encoder: Encoder) throws {
		var container = encoder.container(keyedBy: CodingKeys.self)
		try container.encode(wrapped.aaid, forKey: .aaid)

		var registrationContainer = container.nestedContainer(keyedBy: RegistrationCodingKeys.self, forKey: .registration)
		var registeredAccountsContainer = registrationContainer.nestedUnkeyedContainer(forKey: .registeredAccounts)
		for registeredAccount in wrapped.registration.registeredAccounts {
			var accountContainer = registeredAccountsContainer.nestedContainer(keyedBy: AccountCodingKeys.self)
			try accountContainer.encode(registeredAccount.username, forKey: .username)
			try accountContainer.encode(registeredAccount.server, forKey: .server)
		}

		try container.encode(wrapped.isSupportedByHardware, forKey: .isSupportedByHardware)
		try container.encode(true, forKey: .isSupportedByOs)
		let typedUserEnrollment = TypedUserEnrollment(wrapped: wrapped.userEnrollment)
		try container.encode(typedUserEnrollment, forKey: .userEnrollment)
	}
}
