import { ocdDiv, OnChainDecimal } from '../../types/on-chain-decimal';
import { PollStatus } from './types-poll-new';

function q(pollStatus: PollStatus, e: bigint): OnChainDecimal {
  if (pollStatus.yesVotes + pollStatus.noVotes === 0n)
    return { getOnChainInt: 0n };
  else {
    const q =
      ocdDiv(
        { getOnChainInt: pollStatus.yesVotes },
        { getOnChainInt: BigInt(Math.floor(Math.sqrt(Number(e)))) },
      ).getOnChainInt -
      ocdDiv(
        { getOnChainInt: pollStatus.noVotes },
        {
          getOnChainInt: BigInt(
            Math.floor(
              Math.sqrt(Number(pollStatus.yesVotes + pollStatus.noVotes)),
            ),
          ),
        },
      ).getOnChainInt;

    return { getOnChainInt: BigInt(q) };
  }
}

export function pollPassQuorum(
  pollStatus: PollStatus,
  electorate: bigint,
  minQuorum: bigint,
): boolean {
  return (
    pollStatus.yesVotes + pollStatus.noVotes >= minQuorum &&
    q(pollStatus, electorate).getOnChainInt > 50_000n
  );
}
