import { ethers } from 'ethers';

export function bytes32FromUtf8(label: string, value: string): string {
  return ethers.keccak256(ethers.toUtf8Bytes(`${label}:${value}`));
}

export function instructionIdFromTxHash(txHash: string): string {
  return bytes32FromUtf8('INSTR', txHash);
}

export function uetrFromTxHash(txHash: string): string {
  const h = ethers.keccak256(ethers.toUtf8Bytes(`UETR:${txHash}`));
  const hex = h.slice(2);
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}

export function uetrBytes32FromTxHash(txHash: string): string {
  return ethers.keccak256(ethers.toUtf8Bytes(uetrFromTxHash(txHash)));
}

export function hashShortUtf8(value: string): string {
  if (!value) return ethers.ZeroHash;
  return ethers.keccak256(ethers.toUtf8Bytes(value));
}

/** KTT off-chain test-key attestation per SMART_CONTRACTS_ISO20022_FIN_METHODOLOGY §5.3 */
export function authAttestationHashFromProof(testKeyProof: string, normalizedBody: string): string {
  const proof = testKeyProof.trim();
  const body = normalizedBody.trim();
  if (!proof && !body) return ethers.ZeroHash;
  return ethers.keccak256(ethers.concat([ethers.toUtf8Bytes(proof), ethers.toUtf8Bytes(body)]));
}
