/*
 * Copyright (c) 2025 Onomondo ApS & sysmocom - s.f.m.c. GmbH. All rights reserved.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

#pragma once

#include "length.h"
#include <onomondo/ipa/ipad.h>
#include <onomondo/ipa/utils.h>

#define IPA_NVSTATE_VERSION 3

/* Non volatile state: All struct members in this struct are automatically backed up to a non volatile memory location.
 * (see below). However, this only covers statically allocated struct members. When struct members contain a pointer
 * to a dynamically allocated memory location, then appropriate code must be added to nvstate_serialize,
 * nvstate_deserialize and nvstate_free_contents (see ipad.c). */
struct ipa_nvstate {

	/*! a version flag to make sure we do not load any incompatible nvstate, which was generated by
	 *  a different version of onomondo-ipa */
	uint32_t version;

	/*! internal storage for IoT eUICC emulation. */
	struct {
		int association_token_counter;
		struct ipa_buf *eim_cfg_ber;

		/*! Automatic Profile Enabling configuration (set via configureAutoEnable PSMO) */
		struct {
			bool flag;
			struct ipa_buf *smdp_oid;
			struct ipa_buf *smdp_address;
		} auto_enable;
	} iot_euicc_emu;

} __attribute__((packed));

/*! Context for one IPAd instance. */
struct ipa_context {
	/*! pointer to IPAd configuration options. */
	struct ipa_config *cfg;

	/*! sub-context of the HTTP(s) connection towards the eIM, */
	void *http_ctx;

	/*! sub-context of the smartcard connection towards the eUICC, */
	void *scard_ctx;

	/*! cached eID (read from eUICC when ipa_init is called) */
	uint8_t eid[IPA_LEN_EID];

	/*! volatile internal storage for IoT eUICC emulation. */
	struct {
		/*! cached ICCID of the currently active profile. This ICCID value will be used when a profile rollback is
		 *  performed on a consumer eUICC (in IoT eUICC emulation mode). The value is updated when
		 *  ipa_proc_eucc_pkg_dwnld_exec is called. */
		struct ipa_buf *rollback_iccid;

		/*! cached data to support the emulation of the ES10b function EnableUsingDD */
		struct {
			struct ipa_buf *smdp_oid;
			struct ipa_buf *smdp_address;
			struct ipa_buf *profile_aid;
		} auto_enable;
	} iot_euicc_emu;

	/*! cached eimId (read from eUICC when ipa_init is called) */
	char *eim_id;

	/*! cached eIM address (read from eUICC when ipa_init is called) */
	char *eim_fqdn;

	/*! cached state of generic eUICC package download and execute procedure
	 *  (used from proc_euicc_pkg_dwnld_exec.c, proc_eim_pkg_retr.c and ipad.c) */
	struct ipa_proc_eucc_pkg_dwnld_exec_res *proc_eucc_pkg_dwnld_exec_res;

	/*! Non volatile storage: Everything stored in this struct is loaded by the API user from a non volatile memory
	 *  location on startup (ipa_new_ctx) and stored to a non volatile location on exit (ipa_free_ctx). */
	struct ipa_nvstate nvstate;

	/*! A canary to detect smartcard (eUICC) communication errors */
	bool check_scard;

	/*! A canary to detect HTTP communication errors */
	bool check_http;
};
