import { u8aToHex, hexToU8a, stringToU8a } from '@polkadot/util';
import { parse as uuidParse } from 'uuid';
import { stringToPadded } from './formatters';

export type GetUidProof = {
  did: string;
  uID: string;
  ticker: string;
  confidentialIdentity: any;
};

export const getUidProof = ({
  did,
  uID,
  ticker,
  confidentialIdentity,
}: GetUidProof): any => {
  const u8InvestorDid = hexToU8a(did);
  const u8InvestorUId = uuidParse(uID);
  const u8ScopeDid = stringToU8a(stringToPadded(ticker));

  const cddClaim = JSON.stringify({
    investor_did: Array.from(u8InvestorDid),
    investor_unique_id: Array.from(u8InvestorUId),
  });
  const scopedClaim = JSON.stringify({
    scope_did: Array.from(u8ScopeDid),
    investor_unique_id: Array.from(u8InvestorUId),
  });

  const claimProofString = confidentialIdentity.process_create_claim_proof(
    cddClaim,
    scopedClaim
  );
  const claimProof = JSON.parse(claimProofString);

  Object.keys(claimProof).forEach((key) => {
    claimProof[key] = u8aToHex(claimProof[key]);
  });

  return claimProof;
};
