import { createHash } from "crypto";

const BASE58_ALPHABET =
  "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

export function bs58Decode(input: string): number[] {
  const result: number[] = [];
  let leadingZeros = 0;

  for (let i = 0; i < input.length && input[i] === "1"; i++) {
    leadingZeros++;
  }

  let value = BigInt(0);
  for (let i = leadingZeros; i < input.length; i++) {
    const c = input[i];
    const index = BASE58_ALPHABET.indexOf(c);
    if (index === -1) throw new Error("Invalid Base58 character");
    value = value * BigInt(58) + BigInt(index);
  }

  while (value > 0) {
    result.unshift(Number(value % BigInt(256)));
    value = value / BigInt(256);
  }

  for (let i = 0; i < leadingZeros; i++) {
    result.unshift(0);
  }

  if (result.length < 4) throw new Error("Invalid checksum");

  const payload = result.slice(0, -4);
  const checksum = result.slice(-4);

  const hash1 = createHash("sha256").update(Buffer.from(payload)).digest();
  const hash2 = createHash("sha256").update(hash1).digest();
  const expectedChecksum = hash2.subarray(0, 4);

  if (!Buffer.from(checksum).equals(expectedChecksum)) {
    throw new Error("Invalid checksum");
  }

  return payload;
}
