import { stringToHex } from '@polkadot/util';
import { Polymesh } from '@polymathnetwork/polymesh-sdk';
import { hasUidClaim } from './hasUidClaim';
import { getUidProofFromWallet } from './getUidProofFromWallet';
import { buildApiQueueItem } from './buildApiQueueItem';
import { ApiQueueItem } from '../ui/definition';

export const initApiQueueWithUidCheck = async ({
  sdk,
  did,
  polyWallet,
  ticker,
  condition = true,
  proofErrorHandler,
}: {
  sdk: Polymesh;
  did: string;
  polyWallet: any;
  ticker: string;
  condition?: boolean;
  proofErrorHandler?: (error: Error) => void;
}) => {
  const directApiQueue: ApiQueueItem<any>[] = [];

  if (!condition) return directApiQueue;

  const hasUidAttestation = await hasUidClaim({
    sdk,
    did,
    ticker,
  });

  if (!hasUidAttestation) {
    const proofObj = await getUidProofFromWallet({
      polyWallet,
      ticker,
      errorHandler: proofErrorHandler,
    });
    if (!proofObj) throw Error('Faild to get proof from wallet.');

    const { scope_id: scopeId, cdd_id: cddId, proof } = proofObj;

    const tickerHex = stringToHex(ticker);

    directApiQueue.push(
      buildApiQueueItem({
        method: sdk._polkadotApi.tx.identity.addInvestorUniquenessClaim,
        params: [
          did,
          {
            InvestorUniqueness: [{ Ticker: tickerHex }, scopeId, cddId],
          },
          proof,
          null,
        ],
      })
    );
  }

  return directApiQueue;
};
