import { constructTake } from '@coinweb/contract-kit';
import { extractRead } from '@coinweb/contract-kit/dist/esm/operations/read';

import { getMethodArgs } from './context';
import { extractOps } from './extractOps';

export const extractFunds = () => {
  const { fundsOp } = extractOps();

  const takenFundsIds = getMethodArgs()[7] ?? [];

  if (!fundsOp) {
    return {
      takeOps: [],
      amount: 0n,
    };
  }

  const claims = extractRead(fundsOp);

  const newClaims = claims?.filter(({ content }) => !takenFundsIds.includes((content.key.second_part as [string])[0]));

  if (!newClaims?.length) {
    return {
      takeOps: [],
      amount: 0n,
    };
  }

  return {
    takeOps: newClaims.map(({ content }) => constructTake(content.key)),
    amount: newClaims.reduce((acc, { content }) => acc + BigInt(content.fees_stored), 0n),
  };
};
