import { assert } from "../../../shared/src/asserts.js";
import { WriteTransactionImpl } from "../transactions.js";
import { isLocalMetaDD31, commitFromHash, assertLocalMetaDD31 } from "./commit.js";
import { newWriteLocal } from "./write.js";
async function rebaseMutation(mutation, dagWrite, basisHash, mutators, lc, mutationClientID, formatVersion, zeroData) {
  const localMeta = mutation.meta;
  const name = localMeta.mutatorName;
  if (isLocalMetaDD31(localMeta)) {
    assert(
      localMeta.clientID === mutationClientID,
      "mutationClientID must match clientID of LocalMeta"
    );
  }
  const maybeMutatorImpl = mutators[name];
  if (!maybeMutatorImpl) {
    lc.error?.(`Cannot rebase unknown mutator ${name}`);
  }
  const mutatorImpl = maybeMutatorImpl || (async () => {
  });
  const args = localMeta.mutatorArgsJSON;
  const basisCommit = await commitFromHash(basisHash, dagWrite);
  const nextMutationID = await basisCommit.getNextMutationID(
    mutationClientID,
    dagWrite
  );
  if (nextMutationID !== localMeta.mutationID) {
    throw new Error(
      `Inconsistent mutation ID: original: ${localMeta.mutationID}, next: ${nextMutationID} - mutationClientID: ${mutationClientID} mutatorName: ${name}`
    );
  }
  {
    assertLocalMetaDD31(localMeta);
  }
  const dbWrite = await newWriteLocal(
    basisHash,
    name,
    args,
    mutation.chunk.hash,
    dagWrite,
    localMeta.timestamp,
    mutationClientID,
    formatVersion
  );
  const tx = new WriteTransactionImpl(
    mutationClientID,
    await dbWrite.getMutationID(),
    "rebase",
    zeroData,
    dbWrite,
    lc
  );
  await mutatorImpl(tx, args);
  return dbWrite;
}
async function rebaseMutationAndPutCommit(mutation, dagWrite, basis, mutators, lc, mutationClientID, formatVersion, zeroData) {
  const tx = await rebaseMutation(
    mutation,
    dagWrite,
    basis,
    mutators,
    lc,
    mutationClientID,
    formatVersion,
    zeroData
  );
  return tx.putCommit();
}
async function rebaseMutationAndCommit(mutation, dagWrite, basis, headName, mutators, lc, mutationClientID, formatVersion, zeroData) {
  const dbWrite = await rebaseMutation(
    mutation,
    dagWrite,
    basis,
    mutators,
    lc,
    mutationClientID,
    formatVersion,
    zeroData
  );
  return dbWrite.commit(headName);
}
export {
  rebaseMutationAndCommit,
  rebaseMutationAndPutCommit
};
//# sourceMappingURL=rebase.js.map
