import { Presentation } from '@docknetwork/crypto-wasm-ts';
import b58 from 'bs58';
import stringify from 'json-stringify-deterministic';
import { withExtendedStaticProperties } from '../../../utils/inheritance.js';
import CustomLinkedDataSignature from './CustomLinkedDataSignature.js';
import { isCredVerGte060 } from './DockCryptoSignature.js';
import '../../../utils/types/object.js';
import '../../../utils/types/iterable.js';
import '../../../utils/types/set.js';
import 'jsonld-signatures';
import 'base64url';
import 'jsonld';
import '../../../types/did/document/verification-method-ref.js';
import '../../../types/generic/typed-enum.js';
import '../../../utils/types/array.js';
import 'crypto';
import '../../../utils/interfaces.js';
import '../../../utils/assert.js';
import '../../../utils/error.js';
import 'multiformats/bases/base58';
import 'varint';
import '../../../utils/encoding/ss-58.js';
import 'blake2b';
import '../../../utils/types/bytes.js';
import '../../../utils/types/string.js';
import '../../../types/generic/with-base.js';
import '../../../types/generic/with-catch-null.js';
import '../../../types/generic/with-eq.js';
import '../../../types/generic/any-of.js';
import '../../../types/generic/with-from.js';
import '../../../types/generic/with-from-json-bytes.js';
import '../../../types/generic/typed-null.js';
import '../../../types/generic/create-placeholder.js';
import '../../../types/generic/typed-bytes.js';
import '../../../types/generic/typed-string.js';
import '../../../types/generic/typed-array.js';
import '../../../types/generic/typed-tuple.js';
import '../../../types/generic/typed-number.js';
import '../../../types/generic/typed-set.js';
import '../../../types/generic/typed-map.js';
import '../../../types/generic/typed-struct.js';
import 'uuid';
import 'js-sha256';
import '../../../types/generic/with-qualifier.js';
import '../../../types/generic/utils.js';
import '../../../types/generic/typed-bytes-array.js';
import '../../../types/did/onchain/typed-did/index.js';
import '../../../types/did/onchain/typed-did/did-method-key/did-method-key-public-key.js';
import '../../../utils/encoding/base-58-btc.js';
import '../../../types/generic/sized.js';
import '../../../utils/types/number.js';
import '../../../types/public-keys/public-key.js';
import '../../../types/public-keys/public-key-x25519-value.js';
import '../../../types/public-keys/public-key-ed25519-value.js';
import '../constants.js';
import '../../../types/public-keys/public-key-secp256k1-value.js';
import '../../../types/public-keys/public-key-sr25519-value.js';
import '../../../types/did/onchain/constants.js';
import '../../../types/did/onchain/typed-did/signature.js';
import '../../../types/did/onchain/typed-did/did-method-key/did-method-key-signature.js';
import '../../../types/signatures/signature-value.js';
import '../../../types/signatures/signature-ed25519-value.js';
import '../../../types/signatures/signature-secp256k1-value.js';
import '../../../types/signatures/signature.js';
import '../../../types/signatures/signature-sr25519-value.js';
import '../../../types/did/onchain/typed-did/dock-did-value.js';
import '../../../types/generic/typed-uuid.js';
import '../../../types/did/onchain/typed-did/cheqd-did.js';
import '../../jws.js';
import 'semver/preload.js';

const SUITE_CONTEXT_URL = 'https://www.w3.org/2018/credentials/v1';

const DOCK_ANON_CREDENTIAL_ID = 'dock:anonymous:credential';

/**
 * Defines commons for the `@docknetwork/crypto-wasm-ts` signature proofs.
 */
var DockCryptoSignatureProof = withExtendedStaticProperties(
  ['Signature', 'proofType', 'sigName'],
  class DockCryptoSignatureProof extends CustomLinkedDataSignature {
    /**
     * Default constructor
     * @param options {SignatureSuiteOptions} options for constructing the signature suite
     * @param type
     * @param LDKeyClass
     * @param link
     */
    constructor(options = {}, type, LDKeyClass, link) {
      const { verificationMethod } = options;

      super({
        type,
        LDKeyClass,
        contextUrl: SUITE_CONTEXT_URL,
        alg: type,
        useProofValue: true,
      });

      this.proof = {
        '@context': [
          {
            sec: 'https://w3id.org/security#',
            proof: {
              '@id': 'sec:proof',
              '@type': '@id',
              '@container': '@graph',
            },
          },
          link,
        ],
        type,
      };

      this.verificationMethod = verificationMethod;
      this.accumulatorPublicKeys = options.accumulatorPublicKeys;
      this.predicateParams = options.predicateParams;
      this.circomOutputs = options.circomOutputs;
      this.blindedAttributesCircomOutputs = options.blindedAttributesCircomOutputs;
    }

    async verifyProof({
      proof, document, documentLoader, expansionMap,
    }) {
      try {
        const verificationMethod = await this.getVerificationMethod({
          proof,
          document,
          documentLoader,
          expansionMap,
        });

        const presentationJSON = this.constructor.derivedToAnoncredsPresentation({
          ...document,
          proof,
        });
        const recreatedPres = Presentation.fromJSON(presentationJSON);

        // NOTE: Another example that this credential derivation doesn't work for presentation with more than 1 credential
        const pks = verificationMethod !== undefined
          ? [verificationMethod].map((keyDocument) => {
            const pkRaw = b58.decode(keyDocument.publicKeyBase58);
            return new this.constructor.Signature.KeyPair.PublicKey(pkRaw);
          })
          : [];

        const {
          accumulatorPublicKeys,
          predicateParams,
          circomOutputs,
          blindedAttributesCircomOutputs,
        } = this;

        const expectedAccumulatorPKs = accumulatorPublicKeys
          ? new Map()
          : undefined;
        if (accumulatorPublicKeys) {
          const expectedAccumulatorPK = accumulatorPublicKeys.get(
            document?.credentialStatus?.id,
          );
          if (expectedAccumulatorPK) {
            expectedAccumulatorPKs.set(0, expectedAccumulatorPK);
          }
        }

        const res = recreatedPres.verify(
          pks,
          expectedAccumulatorPKs,
          predicateParams,
          circomOutputs,
          blindedAttributesCircomOutputs,
        );
        if (!res.verified) {
          throw new Error(
            `Invalid anoncreds presentation due to error: ${res.error}`,
          );
        }

        return { verified: true, verificationMethod };
      } catch (error) {
        return { verified: false, error };
      }
    }

    /**
     * Converts a derived proof credential to the native presentation format
     * @param document
     */
    static derivedToAnoncredsPresentation(document) {
      const {
        '@context': context,
        type,
        credentialSchema,
        credentialStatus,
        // issuance date isn't revealed in presentations but for W3C style credential or for the frontend, it needs to be
        // present in the derived credential. Popping it out so that it doesn't end up in `revealedAttributes`. Note that this
        // can be a problem when `issuanceDate` is actually revealed which is rare but a possibility
        issuanceDate: _issuanceDate,
        proof,
        ...revealedAttributes
      } = document;

      // Old prover don't reveal the issuer so remove this field from the revealed attributes
      if (proof.presVersion === undefined) {
        delete revealedAttributes.issuer;
      }

      // ID wasnt revealed but placeholder was used to conform to W3C spec, trim it
      if (revealedAttributes.id === DOCK_ANON_CREDENTIAL_ID) {
        delete revealedAttributes.id;
      }

      const credVersion = proof.version;
      const newCredVersion = isCredVerGte060(credVersion);
      // TODO: This is wrong. This won't work with presentation from 2 or more credentials
      const c = {
        sigType: proof.sigType,
        version: credVersion,
        bounds: proof.bounds,
        schema: newCredVersion
          ? credentialSchema
          : JSON.stringify(credentialSchema),
        revealedAttributes: {
          proof: {
            type: this.sigName,
            verificationMethod: proof.verificationMethod,
          },
          '@context': newCredVersion
            ? stringify(context)
            : JSON.stringify(context),
          type: newCredVersion ? stringify(type) : JSON.stringify(type),
          ...revealedAttributes,
        },
      };
      if (credentialStatus !== undefined) {
        c.status = credentialStatus;
      }
      return {
        // Old credentials incorrectly set the presentation version as credential version which was fine because coincidentally
        // both versions were same. Correcting this mistake now. Once all dependents have upgraded and old presentations don't
        // need to be supported, `proof.presVersion` should be used.
        version:
          proof.presVersion !== undefined ? proof.presVersion : proof.version,
        nonce: proof.nonce,
        context: proof.context,
        spec: {
          credentials: [c],
          attributeEqualities: proof.attributeEqualities,
          boundedPseudonyms: proof.boundedPseudonyms,
          unboundedPseudonyms: proof.unboundedPseudonyms,
        },
        attributeCiphertexts: proof.attributeCiphertexts,
        proof: proof.proofValue,
      };
    }

    /**
     * @param document {object} to be signed.
     * @param proof {object}
     * @param documentLoader {function}
     * @param expansionMap {function}
     */
    async getVerificationMethod({ proof, documentLoader }) {
      return this.constructor.Signature.getVerificationMethod({
        proof,
        documentLoader,
      });
    }
  },
);

export { DOCK_ANON_CREDENTIAL_ID, DockCryptoSignatureProof as default };
//# sourceMappingURL=DockCryptoSignatureProof.js.map
