/*
 * Copyright (c) 2025 Onomondo ApS & sysmocom - s.f.m.c. GmbH. All rights reserved.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 *
 * Author: Philipp Maier <pmaier@sysmocom.de> / sysmocom - s.f.m.c. GmbH
 *
 * See also: GSMA SGP.22, 5.7.7: Function (ES10b): GetEUICCChallenge
 */

#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <onomondo/ipa/mem.h>
#include <onomondo/ipa/utils.h>
#include <onomondo/ipa/scard.h>
#include <onomondo/ipa/log.h>
#include <GetEuiccChallengeRequest.h>
#include <GetEuiccChallengeResponse.h>
#include <Octet16.h>
#include "context.h"
#include "length.h"
#include "utils.h"
#include "euicc.h"
#include "es10x.h"
#include "es10b_get_euicc_chlg.h"

static int dec_get_euicc_chlg(uint8_t *euicc_chlg, const struct ipa_buf *es10b_res)
{
	struct GetEuiccChallengeResponse *asn = NULL;
	uint8_t euicc_chlg_buf[IPA_LEN_EUICC_CHLG];

	asn = ipa_es10x_res_dec(&asn_DEF_GetEuiccChallengeResponse, es10b_res, "GetEuiccChallengeResponse");
	if (!asn)
		return -EINVAL;

	IPA_COPY_ASN_BUF(euicc_chlg_buf, &asn->euiccChallenge);
	memcpy(euicc_chlg, euicc_chlg_buf, sizeof(euicc_chlg_buf));
	ASN_STRUCT_FREE(asn_DEF_GetEuiccChallengeResponse, asn);

	return 0;
}

/*! Function (ES10b): GetEUICCChallenge.
 *  \param[inout] ctx pointer to ipa_context.
 *  \param[out] euicc_chlg challenge generated by eUICC.
 *  \returns 0 on success, negative on error. */
int ipa_es10b_get_euicc_chlg(struct ipa_context *ctx, uint8_t *euicc_chlg)
{
	struct ipa_buf *es10b_req = NULL;
	struct ipa_buf *es10b_res = NULL;
	struct GetEuiccChallengeRequest get_euicc_chlg_req = { 0 };
	int rc = -EINVAL;

	es10b_req =
	    ipa_es10x_req_enc(&asn_DEF_GetEuiccChallengeRequest, &get_euicc_chlg_req, "GetEuiccChallengeRequest");
	if (!es10b_req) {
		IPA_LOGP_ES10X("GetEuiccChallengeRequest", LERROR, "unable to encode ES10b request\n");
		goto error;
	}

	es10b_res = ipa_euicc_transceive_es10x(ctx, es10b_req);
	if (!es10b_res) {
		IPA_LOGP_ES10X("GetEuiccChallengeRequest", LERROR, "no ES10b response\n");
		goto error;
	}

	rc = dec_get_euicc_chlg(euicc_chlg, es10b_res);
	if (rc < 0)
		goto error;

error:
	IPA_FREE(es10b_req);
	IPA_FREE(es10b_res);
	return rc;
}
