

import { CredoError } from "../../error/CredoError.mjs";
import "../../error/index.mjs";
import "../../agent/index.mjs";
import { TypedArrayEncoder } from "../../utils/TypedArrayEncoder.mjs";
import "../../utils/index.mjs";
import { PublicJwk } from "../kms/jwk/PublicJwk.mjs";
import { KeyManagementApi } from "../kms/KeyManagementApi.mjs";
import "../kms/index.mjs";
import { parseDid } from "../dids/domain/parse.mjs";
import { getPublicJwkFromVerificationMethod } from "../dids/domain/key-type/keyDidMapping.mjs";
import { DidResolverService } from "../dids/services/DidResolverService.mjs";
import { DidsApi } from "../dids/DidsApi.mjs";
import "../dids/index.mjs";

//#region src/modules/sd-jwt-vc/utils.ts
async function resolveSigningPublicJwkFromDidUrl(agentContext, didUrl) {
	const { publicJwk } = await agentContext.dependencyManager.resolve(DidsApi).resolveVerificationMethodFromCreatedDidRecord(didUrl);
	return publicJwk;
}
async function resolveDidUrl(agentContext, didUrl) {
	const didDocument = await agentContext.dependencyManager.resolve(DidResolverService).resolveDidDocument(agentContext, didUrl);
	return {
		verificationMethod: didDocument.dereferenceKey(didUrl, ["assertionMethod"]),
		didDocument
	};
}
async function extractKeyFromHolderBinding(agentContext, holder, { forSigning = false, jwkKeyId } = {}) {
	if (holder.method === "did") {
		if (!parseDid(holder.didUrl).fragment) throw new CredoError(`didUrl '${holder.didUrl}' does not contain a '#'. Unable to derive key from did document`);
		let publicJwk;
		if (forSigning) publicJwk = await resolveSigningPublicJwkFromDidUrl(agentContext, holder.didUrl);
		else {
			const { verificationMethod } = await resolveDidUrl(agentContext, holder.didUrl);
			publicJwk = getPublicJwkFromVerificationMethod(verificationMethod);
		}
		const supportedSignatureAlgorithms = publicJwk.supportedSignatureAlgorithms;
		if (supportedSignatureAlgorithms.length === 0) throw new CredoError(`No supported JWA signature algorithms found for key ${publicJwk.jwkTypehumanDescription}`);
		return {
			alg: supportedSignatureAlgorithms[0],
			publicJwk,
			cnf: { kid: holder.didUrl }
		};
	}
	if (holder.method === "jwk") {
		const publicJwk = holder.jwk;
		const alg = publicJwk.supportedSignatureAlgorithms[0];
		if (forSigning) publicJwk.keyId = jwkKeyId ?? publicJwk.legacyKeyId;
		return {
			alg,
			publicJwk,
			cnf: { jwk: publicJwk.toJson() }
		};
	}
	throw new CredoError("Unsupported credential holder binding. Only 'did' and 'jwk' are supported at the moment.");
}
/**
* @todo validate the JWT header (alg)
*/
function getSdJwtSigner(agentContext, key) {
	const kms = agentContext.resolve(KeyManagementApi);
	return async (input) => {
		const result = await kms.sign({
			keyId: key.keyId,
			data: TypedArrayEncoder.fromString(input),
			algorithm: key.signatureAlgorithm
		});
		return TypedArrayEncoder.toBase64URL(result.signature);
	};
}
/**
* @todo validate the JWT header (alg)
*/
function getSdJwtVerifier(agentContext, key) {
	const kms = agentContext.resolve(KeyManagementApi);
	return async (message, signatureBase64Url) => {
		return (await kms.verify({
			signature: TypedArrayEncoder.fromBase64(signatureBase64Url),
			key: { publicJwk: key.toJson() },
			data: TypedArrayEncoder.fromString(message),
			algorithm: key.signatureAlgorithm
		})).verified;
	};
}
function parseHolderBindingFromCredential(payload) {
	if (!payload) throw new CredoError("Unable to extract payload from SD-JWT VC");
	if (!payload.cnf) return null;
	const cnf = payload.cnf;
	if (cnf.jwk) return {
		method: "jwk",
		jwk: PublicJwk.fromUnknown(cnf.jwk)
	};
	if (cnf.kid) {
		if (!cnf.kid.startsWith("did:") || !cnf.kid.includes("#")) throw new CredoError("Invalid holder kid for did. Only absolute KIDs for cnf are supported");
		return {
			method: "did",
			didUrl: cnf.kid
		};
	}
	throw new CredoError("Unsupported credential holder binding. Only 'did' and 'jwk' are supported at the moment.");
}

//#endregion
export { extractKeyFromHolderBinding, getSdJwtSigner, getSdJwtVerifier, parseHolderBindingFromCredential, resolveDidUrl, resolveSigningPublicJwkFromDidUrl };
//# sourceMappingURL=utils.mjs.map