import base64url from 'base64url';
import '../../keypairs/dock-keypair.js';
import Ed25519Keypair from '../../keypairs/keypair-ed25519.js';
import '../../keypairs/keypair-secp256k1.js';
import DidKeypair from '../../keypairs/did-keypair.js';
import '../../resolver/did/did-key-resolver.js';
import '../../resolver/did/did-jwk-resolver.js';
import DIDResolver from '../../resolver/did/did-resolver.js';
import '../../utils/types/array.js';
import { valueBytes } from '../../utils/types/bytes.js';
import 'bs58';
import 'multiformats/bases/base58';
import 'varint';
import '../../utils/encoding/ss-58.js';
import { NoDIDError } from '../abstract/did/errors.js';
import '../abstract/blob/module.js';
import '../abstract/status-list-credential/module.js';
import '../abstract/index.js';
import '../multi-api/accumulator.js';
import '../multi-api/attest.js';
import '../multi-api/blob.js';
import '../multi-api/did.js';
import '../multi-api/offchain-signatures.js';
import '../multi-api/status-list-credential.js';
import '../multi-api/trust-registry.js';
import '../../types/blob/index.js';
import '../../types/attest/index.js';
import '../../types/did/index.js';
import '../../types/generic/typed-enum.js';
import TypedBytes from '../../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-null.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/offchain-signatures/params/index.js';
import '../../types/offchain-signatures/public-keys/index.js';
import '../../types/offchain-signatures/curve-type.js';
import '../../types/payload/cheqd.js';
import '../../types/policy/index.js';
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 '../../types/status-list-credential/index.js';
import '../../types/anchor/index.js';
import '../../types/accumulator/keys.js';
import '../../types/accumulator/params.js';
import '../../types/accumulator/public-key.js';
import '../../types/accumulator/accumulator.js';
import '../../types/accumulator/id.js';
import '../../types/trust-registry/id.js';
import { possibleVerificationMethodRefs, VerificationMethodRef } from '../../types/did/document/verification-method-ref.js';
import { possibleDids } from '../../types/did/onchain/typed-did/index.js';
import { testIf } from './common.js';
import { DidKey } from '../../types/did/onchain/did-key.js';
import { DIDDocument } from '../../types/did/document/index.js';
import { createServiceEndpoint } from '../../types/did/document/service-endpoint.js';
import { BBSPublicKeyValue, BBSPlusPublicKeyValue, PSPublicKeyValue } from '../../types/offchain-signatures/public-keys/value.js';
import '../../utils/inheritance.js';
import '../../utils/types/object.js';
import '../../utils/types/iterable.js';
import '../../utils/types/set.js';
import 'crypto';
import '../../utils/interfaces.js';
import '../../utils/assert.js';
import '../../utils/error.js';
import '../../utils/types/string.js';
import 'blake2b';
import '@stablelib/ed25519';
import '../../vc/crypto/constants.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/create-placeholder.js';
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 'elliptic';
import '../../types/did/document/verification-method-ref-or-ident-ref.js';
import '../../types/did/document/ident-ref.js';
import '../../types/generic/with-qualifier.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/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/typed-uuid.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/params/value.js';
import '../../types/generic/option.js';
import '../../types/offchain-signatures/params/id.js';
import '../../types/generic/with-from-dock-id.js';
import '../../types/generic/with-prop.js';
import '../../types/generic/with-props.js';
import '../../vc/crypto/Bls12381BBDT16KeyPairDock2024.js';
import '@docknetwork/crypto-wasm-ts';
import '../../vc/crypto/common/DockCryptoKeyPair.js';
import '../../vc/crypto/Bls12381BBDT16MACDock2024.js';
import '@docknetwork/crypto-wasm-ts/lib/index.js';
import '../../vc/crypto/common/DockCryptoSignature.js';
import 'jsonld-signatures';
import 'json-stringify-deterministic';
import 'semver/preload.js';
import '../../vc/crypto/common/CustomLinkedDataSignature.js';
import 'jsonld';
import '../../vc/jws.js';
import '../../vc/crypto/Bls12381BBDT16MACProofDock2024.js';
import '../../vc/crypto/common/DockCryptoSignatureProof.js';
import '../../vc/crypto/Bls12381BBSKeyPairDock2023.js';
import '../../vc/crypto/Bls12381BBSSignatureDock2022.js';
import '../../vc/crypto/Bls12381G2KeyPairDock2022.js';
import '../../vc/crypto/Bls12381BBSSignatureDock2023.js';
import '../../vc/crypto/Bls12381BBSSignatureProofDock2022.js';
import '../../vc/crypto/Bls12381BBSSignatureProofDock2023.js';
import '../../vc/crypto/Bls12381BDDT16KeyPairDock2024.js';
import '../../vc/crypto/Bls12381BDDT16MACDock2024.js';
import '../../vc/crypto/Bls12381BDDT16MACProofDock2024.js';
import '../../vc/crypto/Bls12381PSKeyPairDock2023.js';
import '../../vc/crypto/Bls12381PSSignatureDock2023.js';
import '../../vc/crypto/Bls12381PSSignatureProofDock2023.js';
import '@juanelas/base64';
import '@transmute/json-web-signature';
import '../../types/offchain-signatures/public-keys/ref.js';
import '../../types/offchain-signatures/public-keys/id.js';
import '../../types/did/onchain/verification-relationship.js';
import 'key-did-resolver';
import '../../resolver/generic/resolver.js';
import '../../resolver/generic/const.js';
import '../../utils/encoding/base-58.js';
import '../../utils/ident/parsers.js';
import '../../utils/ident/matchers.js';
import '../../types/did/offchain/index.js';
import '../../types/did/offchain/doc-ref.js';
import '../../types/did/onchain/index.js';
import '../../types/did/onchain/controllers.js';
import '../../types/did/onchain/verification-method-signature.js';
import '../../types/did/document/verification-method.js';
import '../../types/generic/with-base58.js';
import '../../types/generic/with-base58btc.js';
import '../../types/generic/with-multibase.js';
import '../../utils/encoding/multibase.js';
import '../../types/did/document/verification-method-type.js';
import '../../types/did/document/verification-method-ref-or-cheqd-verification-method.js';
import '../../types/did/document/const.js';
import '@sphereon/ssi-sdk-ext.did-resolver-jwk';
import '../abstract/did/module.js';
import '../abstract/common/abstract-api-provider.js';
import '../abstract/common/abstract-base-module.js';
import '../abstract/accumulator/module.js';
import '../abstract/common/with-abstract-params.js';
import '../abstract/common/with-abstract-public-keys.js';
import '../../types/blob/id.js';
import '../../types/blob/const.js';
import '../../utils/mappings/dock-did-by-id.js';
import '../../types/blob/blob.js';
import '../../types/policy/one-of-policy-value.js';
import '../../types/status-list-credential/status-list-credential-value.js';
import '../../vc/status-list2021-credential.js';
import '@digitalcredentials/vc-status-list';
import 'pako';
import '../../vc/verifiable-credential.js';
import '../../vc/helpers.js';
import '../../vc/document-loader.js';
import '../../vc/contexts.js';
import '../../vc/contexts/vc-examples-v1.js';
import '../../vc/contexts/security_context.js';
import '../../vc/contexts/status-list-21.js';
import '../../vc/contexts/private-status-list-21.js';
import '../../utils/json-fetch.js';
import '../../vc/crypto/EcdsaSecp256k1Signature2019.js';
import '../../vc/crypto/EcdsaSecp256k1VerificationKey2019.js';
import '../../vc/crypto/Ed25519Signature2018.js';
import '../../vc/crypto/Ed25519VerificationKey2018.js';
import '../../vc/crypto/Ed25519Signature2020.js';
import '../../vc/crypto/Ed25519VerificationKey2020.js';
import '../../vc/crypto/JsonWebSignature2020.js';
import '../../vc/credentials.js';
import '../../vc/CredentialIssuancePurpose.js';
import '../../vc/schema.js';
import 'jsonschema';
import '../../vc/constants.js';
import '../../vc/revocation.js';
import 'blakejs';
import '../../utils/ident/ensure-ident.js';
import '../../types/status-list-credential/id.js';
import '../../types/accumulator/variants.js';
import '../abstract/anchor/module.js';
import 'mrklt';
import '../abstract/attest/module.js';
import '../abstract/offchain-signatures/module.js';
import '../abstract/trust-registry/module.js';
import '../abstract/schema/module.js';
import 'json-canonicalize';
import '../../vc/schemas/schema-draft-07.js';
import '../multi-api/common.js';
import '../../types/trust-registry/index.js';
import '../../types/trust-registry/schema.js';
import '../../types/trust-registry/issuer.js';
import '../../types/trust-registry/verifier.js';

// eslint-disable-next-line jest/no-export
function generateDIDModuleTests(
  { did: module },
  { Did, ParamsId },
  filter = () => true,
) {
  const test = testIf(filter);

  describe(`Using ${module.constructor.name} with ${Did.name}`, () => {
    test('Creates basic `DIDDocument` with keys', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      const document = DIDDocument.create(did, [didKeypair.didKey()]);

      await module.createDocument(document, didKeypair);

      expect((await module.getDocument(did)).eq(document)).toBe(true);
    });

    test('Creates and resolves `DIDDocument` with `JsonWebKey2020` controller key', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);
      const keyId = `${did}#keys-1`;
      const publicKeyJwk = {
        crv: 'Ed25519',
        kty: 'OKP',
        x: base64url.encode(Buffer.from(valueBytes(keyPair.publicKey()))),
      };

      const document = DIDDocument.from({
        '@context': [
          'https://www.w3.org/ns/did/v1',
          'https://w3id.org/security/suites/jws-2020/v1',
        ],
        id: String(did),
        controller: [String(did)],
        verificationMethod: [
          {
            id: keyId,
            type: 'JsonWebKey2020',
            controller: String(did),
            publicKeyJwk,
          },
        ],
        authentication: [keyId],
        assertionMethod: [keyId],
        keyAgreement: [],
        capabilityInvocation: [keyId],
        capabilityDelegation: [],
        service: [],
      });

      await module.createDocument(document, didKeypair);
      const storedDocument = await module.getDocument(did);
      const storedJSON = storedDocument.toJSON();
      const possibleDidIds = new Set(possibleDids(did));
      const possibleMethodIds = new Set(possibleVerificationMethodRefs(keyId));
      const storedMethod = storedJSON.verificationMethod.find(
        (method) => possibleMethodIds.has(method.id),
      );

      expect(possibleDidIds.has(storedJSON.id)).toBe(true);
      expect(storedMethod).toMatchObject({
        type: 'JsonWebKey2020',
      });
      expect(possibleDidIds.has(storedMethod.controller)).toBe(true);
      expect(storedMethod.publicKeyJwk).toEqual(publicKeyJwk);
      expect(storedJSON.authentication.some((methodId) => possibleMethodIds.has(methodId))).toBe(true);
      expect(storedJSON.assertionMethod.some((methodId) => possibleMethodIds.has(methodId))).toBe(true);

      const resolver = new DIDResolver(module);
      expect(
        DIDDocument.from(await resolver.resolve(String(did))).eq(storedDocument),
      ).toBe(true);
    });

    test('Creates `DIDDocument` containing BBS/BBSPlus/PS keys', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      const paramsRef = [did, ParamsId.random()];

      const bbsKey = new BBSPublicKeyValue(TypedBytes.random(100), paramsRef);
      const bbsPlusKey = new BBSPlusPublicKeyValue(
        TypedBytes.random(100),
        paramsRef,
      );
      const psKey = new PSPublicKeyValue(TypedBytes.random(1000), paramsRef);

      const document = DIDDocument.create(did, [
        didKeypair.didKey(),
        new DidKey(bbsKey),
        new DidKey(bbsPlusKey),
        new DidKey(psKey),
      ]);

      await module.createDocument(document, didKeypair);

      expect((await module.getDocument(did)).eq(document)).toBe(true);
    });

    test('Updates `DIDDocument` containing BBS/BBSPlus/PS keys', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      const bbsKey = new DidKey(new BBSPublicKeyValue(TypedBytes.random(100)));
      const bbsPlusKey = new DidKey(
        new BBSPlusPublicKeyValue(TypedBytes.random(100)),
      );
      const psKey = new DidKey(new PSPublicKeyValue(TypedBytes.random(1000)));

      const document = DIDDocument.create(did, [didKeypair.didKey()]);

      await module.createDocument(document, didKeypair);

      expect((await module.getDocument(did)).eq(document)).toBe(true);

      document.addKey([did, document.nextKeyIndex()], bbsKey);
      document.addKey([did, document.nextKeyIndex()], bbsPlusKey);
      document.addKey([did, document.nextKeyIndex()], psKey);

      await module.updateDocument(document, didKeypair);

      expect((await module.getDocument(did)).eq(document)).toBe(true);

      expect(document.didKeys().toJSON()).toEqual([
        [
          didKeypair.verificationMethodId.toJSON(),
          didKeypair.didKey().toJSON(),
        ],
        [new VerificationMethodRef(did, 2).toJSON(), bbsKey.toJSON()],
        [new VerificationMethodRef(did, 3).toJSON(), bbsPlusKey.toJSON()],
        [new VerificationMethodRef(did, 4).toJSON(), psKey.toJSON()],
      ]);
    });

    test('Creates `DIDDocument` containing services', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      const service1 = createServiceEndpoint('LinkedDomains', [
        'ServiceEndpoint',
      ]);
      const service2 = createServiceEndpoint('DIDCommMessaging', [
        {
          uri: 'https://example.com/path1',
        },
      ]);

      const document = DIDDocument.create(did, [didKeypair.didKey()], [], {
        service1,
        service2,
      });

      await module.createDocument(document, didKeypair);

      expect((await module.getDocument(did)).eq(document)).toBe(true);
    });

    test('Creates `DIDDocument` containing DIDComm services with full structure', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      // Test DIDComm service with full object structure
      const expectedServiceData = {
        uri: 'https://example.com/path3',
        accept: [
          'didcomm/v2',
          'didcomm/aip2;env=rfc587',
        ],
        routingKeys: ['did:example:somemediator#somekey'],
        recipientKeys: ['did:example:somerecipient#somekey'],
        priority: 0,
      };

      const didCommService = createServiceEndpoint('DIDCommMessaging', [expectedServiceData]);
      const document = DIDDocument.create(did, [didKeypair.didKey()], [], {
        didcomm: didCommService,
      });

      const createTx = (await module.createDocumentTx(document, didKeypair)).toJSON();

      expect(JSON.parse(JSON.stringify(createTx.value.payload.service[0]))).toMatchObject({
        id: expect.anything(),
        serviceType: 'DIDCommMessaging',
        serviceEndpoint: [
          expectedServiceData.uri,
        ],
        recipientKeys: expectedServiceData.recipientKeys,
        routingKeys: expectedServiceData.routingKeys,
        accept: expectedServiceData.accept,
        priority: expectedServiceData.priority,
      });

      await module.createDocument(document, didKeypair);

      // Verify the DIDComm service data structure is preserved
      const retrievedDocument = await module.getDocument(did);
      const retrievedJSON = retrievedDocument.toJSON();

      // Verify the document equality
      expect((await module.getDocument(did)).eq(document)).toBe(true);

      // Find the DIDComm service in the retrieved document
      const didCommServiceInRetrieved = retrievedJSON.service.find((service) => service.type === 'DIDCommMessaging');

      expect(didCommServiceInRetrieved).toBeDefined();
      expect(didCommServiceInRetrieved.serviceEndpoint).toHaveLength(1);

      const retrievedServiceEndpoint = didCommServiceInRetrieved.serviceEndpoint[0];

      // Verify each field individually
      expect(retrievedServiceEndpoint.uri).toBe(expectedServiceData.uri);
      expect(retrievedServiceEndpoint.accept).toEqual(expectedServiceData.accept);
      expect(retrievedServiceEndpoint.routingKeys).toEqual(expectedServiceData.routingKeys);
      expect(retrievedServiceEndpoint.recipientKeys).toEqual(expectedServiceData.recipientKeys);
      expect(retrievedServiceEndpoint.priority).toEqual(expectedServiceData.priority);

      // Also verify the entire object matches
      expect(retrievedServiceEndpoint).toEqual(expectedServiceData);
    });

    test('Serialize and deserialize `DIDDocument` gives same result', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      const service1 = createServiceEndpoint('LinkedDomains', [
        'ServiceEndpoint',
      ]);
      const service2 = createServiceEndpoint('DIDCommMessaging', [
        {
          uri: 'https://example.com/path',
          accept: [],
          routingKeys: [],
        },
      ]);

      const document = DIDDocument.create(did, [didKeypair.didKey()]);
      document.addServiceEndpoint([did, 'service1'], service1);
      document.addServiceEndpoint([did, 'service2'], service2);

      const documentJSON = document.toJSON();

      const restoredDocument = DIDDocument.from(documentJSON);
      const restoredJSON = restoredDocument.toJSON();

      expect(restoredJSON).toMatchObject(documentJSON);
      expect(restoredDocument.eq(document)).toBe(true);
    });

    test('Updates `DIDDocument` containing services', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      const service1 = createServiceEndpoint('LinkedDomains', [
        'ServiceEndpoint',
      ]);
      const service2 = createServiceEndpoint('DIDCommMessaging', [
        {
          uri: 'https://example.com/path',
          accept: [],
          routingKeys: [],
        },
      ]);

      const document = DIDDocument.create(did, [didKeypair.didKey()]);

      await module.createDocument(document, didKeypair);

      expect((await module.getDocument(did)).eq(document)).toBe(true);

      document.addServiceEndpoint([did, 'service1'], service1);
      document.addServiceEndpoint([did, 'service2'], service2);

      await module.updateDocument(document, didKeypair);

      expect((await module.getDocument(did)).eq(document)).toBe(true);

      document.removeServiceEndpoint([did, 'service2']);

      await module.updateDocument(document, didKeypair);

      expect((await module.getDocument(did)).eq(document)).toBe(true);

      expect(document.service.length).toEqual(1);
    });

    test("Updates `DIDDocument`'s keys", async () => {
      const did = Did.random();

      const keyPair1 = Ed25519Keypair.random();
      const keyPair2 = Ed25519Keypair.random();
      const keyPair3 = Ed25519Keypair.random();

      const didKeypair1 = new DidKeypair([did, 1], keyPair1);
      const didKeypair2 = new DidKeypair([did, 2], keyPair2);
      const didKeypair3 = new DidKeypair([did, 3], keyPair3);

      const document = DIDDocument.create(did, [
        didKeypair1.didKey(),
        didKeypair2.didKey(),
      ]);

      await module.createDocument(document, didKeypair2);
      expect((await module.getDocument(did)).eq(document)).toBe(true);

      document.removeKey([did, 2]);
      await module.updateDocument(document, didKeypair1);
      expect((await module.getDocument(did)).eq(document)).toBe(true);

      document.addKey([did, 3], didKeypair3.didKey());
      await expect(() => module.updateDocument(document, didKeypair2)).rejects.toThrow();

      await module.updateDocument(document, didKeypair1);
      expect((await module.getDocument(did)).eq(document)).toBe(true);
    });

    test('Removes (deactivates) `DIDDocument`', async () => {
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      const document = DIDDocument.create(did, [didKeypair.didKey()]);

      await module.createDocument(document, didKeypair);
      expect((await module.getDocument(did)).eq(document)).toBe(true);

      await module.removeDocument(did, didKeypair);
      await expect(() => module.getDocument(did)).rejects.toThrow(
        new NoDIDError(did),
      );
    });

    test("Throws an error if `DIDDocument` doesn't exist", async () => {
      const did = Did.random();

      await expect(() => module.getDocument(did)).rejects.toThrow(
        new NoDIDError(did),
      );
    });

    test('`DIDResolver`', async () => {
      const resolver = new DIDResolver(module);
      const did = Did.random();

      const keyPair = Ed25519Keypair.random();
      const didKeypair = new DidKeypair([did, 1], keyPair);

      const document = DIDDocument.create(did, [didKeypair.didKey()]);

      await module.createDocument(document, didKeypair);

      expect(
        DIDDocument.from(await resolver.resolve(String(did))).eq(document),
      ).toBe(true);
    });
  });
}

export { generateDIDModuleTests as default };
//# sourceMappingURL=did-module.js.map
