import { FEED_INDEX_HEX_LENGTH } from "../types/index.js";
import { keccak256Hash } from "../utils/hash.js";
import { hexToBytes, makeHexString } from "../utils/hex.js";
import { writeUint64BigEndian } from "../utils/uint64.js";

function isEpoch(epoch) {
  return typeof epoch === 'object' && epoch !== null && 'time' in epoch && 'level' in epoch;
}

function hashFeedIdentifier(topic, index) {
  return keccak256Hash(hexToBytes(topic), index);
}

function makeSequentialFeedIdentifier(topic, index) {
  const indexBytes = writeUint64BigEndian(index);
  return hashFeedIdentifier(topic, indexBytes);
}

function makeFeedIndexBytes(s) {
  const hex = makeHexString(s, FEED_INDEX_HEX_LENGTH);
  return hexToBytes(hex);
}

export function makeFeedIdentifier(topic, index) {
  if (typeof index === 'number') {
    return makeSequentialFeedIdentifier(topic, index);
  } else if (typeof index === 'string') {
    const indexBytes = makeFeedIndexBytes(index);
    return hashFeedIdentifier(topic, indexBytes);
  } else if (isEpoch(index)) {
    throw new TypeError('epoch is not yet implemented');
  }

  return hashFeedIdentifier(topic, index);
}