import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';
import * as dagPB from '@ipld/dag-pb';
import { CID } from 'multiformats/cid';
import { sha256 } from 'multiformats/hashes/sha2';
import { expect } from 'aegir/utils/chai.js';
import {
  getDescribe,
  getIt
} from '../../utils/mocha.js';
export function testAddLink(factory, options) {
  const describe = getDescribe(options);
  const it = getIt(options);
  describe('.object.patch.addLink', function () {
    this.timeout(80 * 1000);
    let ipfs;
    before(async () => {
      ipfs = (await factory.spawn()).api;
    });
    after(() => factory.clean());
    it('should add a link to an existing node', async () => {
      const obj = {
        Data: uint8ArrayFromString('patch test object'),
        Links: []
      };
      const node2 = {
        Data: uint8ArrayFromString('some other node'),
        Links: []
      };
      await ipfs.object.put(node2);
      const node2Buf = dagPB.encode(node2);
      const link = {
        Name: 'link-to-node',
        Tsize: node2Buf.length,
        Hash: CID.createV0(await sha256.digest(node2Buf))
      };
      const node1a = {
        Data: obj.Data,
        Links: obj.Links
      };
      const node1b = {
        Data: node1a.Data,
        Links: [link]
      };
      const node1bCid = await ipfs.object.put(node1b);
      const testNodeCid = await ipfs.object.put(obj);
      const cid = await ipfs.object.patch.addLink(testNodeCid, link);
      expect(node1bCid).to.eql(cid);
    });
    it('returns error for request without arguments', () => {
      return expect(ipfs.object.patch.addLink(null, null, null)).to.eventually.be.rejected.and.be.an.instanceOf(Error);
    });
    it('returns error for request with only one invalid argument', () => {
      return expect(ipfs.object.patch.addLink('invalid', null, null)).to.eventually.be.rejected.and.be.an.instanceOf(Error);
    });
  });
}