const require_rolldown_runtime = require('../../../../../_virtual/rolldown_runtime.js');
const require_SignatureDecorator = require('./SignatureDecorator.js');
let __credo_ts_core = require("@credo-ts/core");
__credo_ts_core = require_rolldown_runtime.__toESM(__credo_ts_core);

//#region ../didcomm/src/decorators/signature/SignatureDecoratorUtils.ts
/**
* Unpack and verify signed data before casting it to the supplied type.
*
* @param decorator Signature decorator to unpack and verify
* @param wallet wallet instance
*
* @return Resulting data
*/
async function unpackAndVerifySignatureDecorator(agentContext, decorator) {
	const signerVerkey = decorator.signer;
	const kms = agentContext.dependencyManager.resolve(__credo_ts_core.Kms.KeyManagementApi);
	const publicJwk = __credo_ts_core.Kms.PublicJwk.fromPublicKey({
		kty: "OKP",
		crv: "Ed25519",
		publicKey: __credo_ts_core.TypedArrayEncoder.fromBase58(signerVerkey)
	});
	const signedData = __credo_ts_core.TypedArrayEncoder.fromBase64(decorator.signatureData);
	const signature = __credo_ts_core.TypedArrayEncoder.fromBase64(decorator.signature);
	if (!(await kms.verify({
		algorithm: "EdDSA",
		data: signedData,
		key: { publicJwk: publicJwk.toJson() },
		signature
	})).verified) throw new __credo_ts_core.CredoError("Signature is not valid");
	return __credo_ts_core.JsonEncoder.fromBuffer(signedData.slice(8));
}
/**
* Sign data supplied and return a signature decorator.
*
* @param data the data to sign
* @param wallet the wallet containing a key to use for signing
* @param signerKey signer key
*
* @returns Resulting signature decorator.
*/
async function signData(agentContext, data, signerKey) {
	const kms = agentContext.dependencyManager.resolve(__credo_ts_core.Kms.KeyManagementApi);
	const dataBuffer = __credo_ts_core.Buffer.concat([__credo_ts_core.utils.timestamp(), __credo_ts_core.JsonEncoder.toBuffer(data)]);
	const result = await kms.sign({
		data: dataBuffer,
		algorithm: "EdDSA",
		keyId: signerKey.keyId
	});
	return new require_SignatureDecorator.SignatureDecorator({
		signatureType: "https://didcomm.org/signature/1.0/ed25519Sha512_single",
		signature: __credo_ts_core.TypedArrayEncoder.toBase64URL(result.signature),
		signatureData: __credo_ts_core.TypedArrayEncoder.toBase64URL(dataBuffer),
		signer: __credo_ts_core.TypedArrayEncoder.toBase58(signerKey.publicKey.publicKey)
	});
}

//#endregion
exports.signData = signData;
exports.unpackAndVerifySignatureDecorator = unpackAndVerifySignatureDecorator;