import { createList, createCredential, StatusList, decodeList } from '@digitalcredentials/vc-status-list';
import { ungzip, gzip } from 'pako';
import { u8aToU8a } from '../utils/types/bytes.js';
import VerifiableCredential from './verifiable-credential.js';
import '../utils/types/array.js';
import 'bs58';
import 'multiformats/bases/base58';
import 'varint';
import '../utils/encoding/ss-58.js';
import { ensureStatusListId } from '../utils/ident/ensure-ident.js';
import 'jsonld';
import '@transmute/json-web-signature';
import './crypto/Bls12381BBDT16KeyPairDock2024.js';
import './crypto/Bls12381BBDT16MACDock2024.js';
import './crypto/Bls12381BBDT16MACProofDock2024.js';
import './crypto/Bls12381BBSKeyPairDock2023.js';
import './crypto/Bls12381BBSSignatureDock2022.js';
import './crypto/Bls12381BBSSignatureDock2023.js';
import './crypto/Bls12381BBSSignatureProofDock2022.js';
import './crypto/Bls12381BBSSignatureProofDock2023.js';
import './crypto/Bls12381BDDT16KeyPairDock2024.js';
import './crypto/Bls12381BDDT16MACDock2024.js';
import './crypto/Bls12381BDDT16MACProofDock2024.js';
import './crypto/Bls12381G2KeyPairDock2022.js';
import './crypto/Bls12381PSKeyPairDock2023.js';
import './crypto/Bls12381PSSignatureDock2023.js';
import './crypto/Bls12381PSSignatureProofDock2023.js';
import '@juanelas/base64';
import '../keypairs/keypair-secp256k1.js';
import './crypto/common/CustomLinkedDataSignature.js';
import '@stablelib/ed25519';
import '../types/public-keys/public-key.js';
import '../types/public-keys/public-key-sr25519-value.js';
import '../types/public-keys/public-key-ed25519-value.js';
import '../types/public-keys/public-key-secp256k1-value.js';
import '../types/public-keys/public-key-x25519-value.js';
import '../types/signatures/signature-value.js';
import '../types/signatures/signature.js';
import '../keypairs/dock-keypair.js';
import '../types/did/onchain/did-key.js';
import '../types/did/document/verification-method-ref-or-ident-ref.js';
import '../types/did/onchain/typed-did/index.js';
import '../types/did/document/verification-method-ref.js';
import 'crypto';
import '../utils/interfaces.js';
import '../utils/assert.js';
import '../utils/error.js';
import '../utils/types/string.js';
import '../utils/types/iterable.js';
import '../utils/types/object.js';
import '../utils/inheritance.js';
import '../utils/types/set.js';
import './helpers.js';
import './document-loader.js';
import './contexts.js';
import './contexts/vc-examples-v1.js';
import './contexts/security_context.js';
import './contexts/status-list-21.js';
import './contexts/private-status-list-21.js';
import '../utils/json-fetch.js';
import './crypto/EcdsaSecp256k1Signature2019.js';
import './crypto/constants.js';
import './crypto/EcdsaSecp256k1VerificationKey2019.js';
import '../utils/encoding/multibase.js';
import './crypto/Ed25519Signature2018.js';
import './crypto/Ed25519VerificationKey2018.js';
import '../keypairs/keypair-ed25519.js';
import '../types/generic/typed-enum.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 'blake2b';
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/sized.js';
import '../utils/types/number.js';
import '../types/signatures/signature-ed25519-value.js';
import '../types/signatures/signature-secp256k1-value.js';
import '../types/signatures/signature-sr25519-value.js';
import './crypto/Ed25519Signature2020.js';
import './crypto/Ed25519VerificationKey2020.js';
import './crypto/JsonWebSignature2020.js';
import '../keypairs/did-keypair.js';
import '../types/offchain-signatures/params/index.js';
import '../types/offchain-signatures/params/value.js';
import '../types/generic/option.js';
import '../types/offchain-signatures/curve-type.js';
import '../types/offchain-signatures/params/id.js';
import '../types/generic/typed-uuid.js';
import '../types/generic/with-from-dock-id.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/with-qualifier.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/did/onchain/typed-did/dock-did-value.js';
import '../types/generic/utils.js';
import '../types/generic/typed-bytes-array.js';
import '../types/did/onchain/typed-did/cheqd-did.js';
import '../types/offchain-signatures/public-keys/index.js';
import '../types/generic/with-prop.js';
import '../types/generic/with-props.js';
import '../types/offchain-signatures/public-keys/value.js';
import '../types/offchain-signatures/public-keys/ref.js';
import '../types/offchain-signatures/public-keys/id.js';
import '@docknetwork/crypto-wasm-ts';
import './crypto/common/DockCryptoKeyPair.js';
import '@docknetwork/crypto-wasm-ts/lib/index.js';
import './crypto/common/DockCryptoSignature.js';
import 'jsonld-signatures';
import 'json-stringify-deterministic';
import 'semver/preload.js';
import 'base64url';
import './jws.js';
import './crypto/common/DockCryptoSignatureProof.js';
import 'elliptic';
import '../types/did/onchain/verification-relationship.js';
import '../types/did/document/ident-ref.js';
import './credentials.js';
import './CredentialIssuancePurpose.js';
import './schema.js';
import 'jsonschema';
import './constants.js';
import './revocation.js';
import 'blakejs';
import '../utils/ident/matchers.js';

/**
 * Status list 2021 verifiable credential as per https://www.w3.org/TR/vc-status-list/#statuslist2021credential.
 */
class StatusList2021Credential extends VerifiableCredential {
  static Type = 'statusList2021';

  /**
   * Create a new Status List 2021 Verifiable Credential instance.
   * @param {string} id - id of the credential
   */
  constructor(id) {
    super(id);

    // Caches decoded status list.
    Object.defineProperty(this, 'internalCachedStatusList', {
      value: { encoded: void 0, decoded: void 0 },
      writable: true,
    });
  }

  /**
   * Fail if the given verifiable credential id isn't a valid `StatusList2021Credential` id.
   * @param {*} id
   */
  static verifyID(id) {
    ensureStatusListId(id);
  }

  /**
   * Creates new `StatusList2021Credential` with supplied `id` and option `statusPurpose` = `revocation` by default,
   * `length` and `revokeIndices`. Note that credential with `statusPurpose` = `revocation` can't unsuspend its indices.
   * To allow unrevoking indices in the future, use `statusPurpose` = `suspension`.
   * The proof will be generated immediately using supplied `keyDoc`.
   *
   * @param {KeyDoc} keyDoc
   * @param {string} id - on-chain hex identifier for the `StatusList2021Credential`.
   * @param {object} [params={}]
   * @param {'revocation'|'suspension'} [params.statusPurpose=revocation] - `statusPurpose` of the `StatusList2021Credential`.
   * Can be either `revocation` or `suspension`.
   * @param {number} [params.length=1e4] - length of the underlying `StatusList`.
   * @param {Iterable<number>} [params.revokeIndices=[]] - iterable producing indices to be revoked or suspended initially
   * @returns {Promise<StatusList2021Credential>}
   */
  static async create(
    keyDoc,
    id,
    { statusPurpose = 'revocation', length = 1e4, revokeIndices = [] } = {},
  ) {
    const statusList = await createList({ length });
    this.updateStatusList(statusPurpose, statusList, revokeIndices);

    const jsonCred = await createCredential({
      id: String(id),
      list: statusList,
      statusPurpose,
    });

    const cred = this.fromJSON(jsonCred);

    return await cred.sign(keyDoc);
  }

  /**
   * Revokes indices and unsuspends other indices in the underlying status list, regenerating the proof.
   * If `statusPurpose` = `revocation`, indices can't be unsuspended.
   * The status list revoked (suspended)/unsuspended indices will be set atomically and in case of an error,
   * the underlying value won't be modified.
   * Throws an error if the underlying status list can't be decoded or any of the supplied indices is out of range.
   *
   * @param {KeyDoc} keyDoc
   * @param {object} [update={}]
   * @param {Iterable<number>} update.revokeIndices - indices to be revoked or suspended
   * @param {Iterable<number>} update.unsuspendIndices - indices to be unsuspended
   * @returns {Promise<this>}
   */
  async update(keyDoc, { revokeIndices = [], unsuspendIndices = [] }) {
    const currentStatusList = await this.decodedStatusList();
    const statusList = new StatusList({
      buffer: new Uint8Array(currentStatusList.bitstring.bits),
    });

    this.constructor.updateStatusList(
      this.credentialSubject.statusPurpose,
      statusList,
      revokeIndices,
      unsuspendIndices,
    );

    this.credentialSubject.encodedList = await statusList.encode();
    // Remove `proof` so that an array of `proof`s is not created by the following `sign` call.
    delete this.proof;
    this.setIssuanceDate(new Date().toISOString());

    await this.sign(keyDoc);

    return this;
  }

  /**
   * Returns a `Promise` resolving to the decoded `StatusList`.
   *
   * @returns {Promise<StatusList>}
   */
  async decodedStatusList() {
    const { encoded, decoded } = this.internalCachedStatusList;

    if (encoded === this.credentialSubject.encodedList && decoded !== void 0) {
      return decoded;
    } else {
      this.internalCachedStatusList = {
        encoded: this.credentialSubject.encodedList,
        decoded: decodeList(this.credentialSubject),
      };

      return this.internalCachedStatusList.decoded;
    }
  }

  /**
   * Returns `true` if given index is revoked or suspended, `false` otherwise.
   * Throws an error if the underlying status list can't be decoded or supplied index is out of range.
   *
   * @param {number} index
   * @returns {Promise<boolean>}
   */
  async revoked(index) {
    const decodedStatusList = await this.decodedStatusList();

    return decodedStatusList.getStatus(index);
  }

  /**
   * Accepts an iterable of indices to be checked and returns an array containing `true` in the positions
   * of revoked (suspended) indices and `false` for non-revoked (non-suspended) indices.
   * Throws an error if the underlying status list can't be decoded or any of supplied indices is out of range.
   *
   * @param {Iterable<number>} indices
   * @returns {Promise<Array<boolean>>}
   */
  async revokedBatch(indices) {
    const decodedStatusList = await this.decodedStatusList();

    return [...indices].map((index) => decodedStatusList.getStatus(index));
  }

  /**
   * Decodes `StatusList2021Credential` from provided bytes.
   * @param {Uint8Array} bytes
   */
  static fromBytes(bytes) {
    const gzipBufferCred = Buffer.from(u8aToU8a(bytes));
    const stringifiedCred = ungzip(gzipBufferCred, { to: 'string' });
    const parsedCred = JSON.parse(stringifiedCred);

    return this.fromJSON(parsedCred);
  }

  /**
   * Instantiates `StatusList2021Credential` from the provided `JSON`.
   *
   * @param {object} json
   * @returns {StatusList2021Credential}
   */
  static fromJSON(json) {
    const cred = super.fromJSON(json);
    cred.validate();

    return cred;
  }

  /**
   * Converts `StatusList2021Credential` to its JSON representation.
   * @returns {object}
   */
  toJSON() {
    this.validate();

    return super.toJSON();
  }

  /**
   * Encodes `StatusList2021Credential` as bytes.
   * @returns {Uint8Array}
   */
  toBytes() {
    const jsonCred = this.toJSON();
    const stringifiedCred = JSON.stringify(jsonCred);
    const bufferCred = Buffer.from(stringifiedCred);

    return gzip(bufferCred);
  }

  /**
   * Validates underlying `StatusList2021Credential`.
   */
  validate() {
    const { credentialSubject } = this;

    if (!credentialSubject) throw new Error('Missing `credentialSubject`');
    if (!this.constructor.statusPurposes.has(credentialSubject.statusPurpose)) {
      throw new Error(
        `Invalid \`statusPurpose\`, expected one of \`${[
          ...this.constructor.statusPurposes,
        ].join(', ')}\``,
      );
    }
    if (typeof credentialSubject.id !== 'string' || !credentialSubject.id) {
      throw new Error('Missing `credentialSubject.id`');
    }
    if (credentialSubject.type !== 'StatusList2021') {
      throw new Error(
        '`credentialSubject.type` must be set to `StatusList2021`',
      );
    }
    if (!credentialSubject.encodedList) {
      throw new Error('`credentialSubject.encodedList` must be present');
    }
  }

  /**
   * Revokes (suspends) `revokeIndices` and unsuspends `unsuspendIndices` from the supplied `StatusList`.
   *
   * Throws an error if
   * - non-empty `unsuspendIndices` passed along with `statusPurpose != suspension`
   * - any index is present in both iterables
   * - some index is out of bounds.
   *
   * @param {'revocation'|'suspension'} statusPurpose
   * @param {StatusList} statusList
   * @param {Iterable<number>} revokeIndices
   * @param {Iterable<number>} unsuspendIndices
   */
  static updateStatusList(
    statusPurpose,
    statusList,
    revokeIndices = [],
    unsuspendIndices = [],
  ) {
    const unsuspendIndiceSet = new Set(unsuspendIndices);
    if (statusPurpose !== 'suspension' && unsuspendIndiceSet.size > 0) {
      throw new Error(
        `Can't unsuspend indices for credential with \`statusPurpose\` = \`${statusPurpose}\`, it's only possible with \`statusPurpose\` = \`suspension\``,
      );
    }

    for (const idx of revokeIndices) {
      if (unsuspendIndiceSet.has(idx)) {
        throw new Error(
          `Index \`${idx}\` appears in both revoke and unsuspend sets`,
        );
      }

      statusList.setStatus(idx, true);
    }
    for (const idx of unsuspendIndiceSet) {
      statusList.setStatus(idx, false);
    }
  }
}

/**
 * Allowed status purposes for this credential type.
 */
StatusList2021Credential.statusPurposes = new Set(['revocation', 'suspension']);

export { StatusList2021Credential as default };
//# sourceMappingURL=status-list2021-credential.js.map
