import { extractErrorMsg } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs";
import { getIbGibAddr } from "@ibgib/ts-gib/dist/helper.mjs";
import { rel8 } from "@ibgib/ts-gib/dist/V1/transforms/rel8.mjs";
import { GLOBAL_LOG_A_LOT } from "../../core-constants.mjs";
import { TAG_TARGET_REL8N_NAME } from "./tag-constants.mjs";
const logalot = GLOBAL_LOG_A_LOT;
/**
 * relates an ibgib provided by {@link ibGib} or {@link addr} to the latest
 * version of the given {@link tagIbGib}.
 *
 * persists this result in the same {@link space} and registers the newly
 * created tag ibgib via the {@link metaspace}.
 *
 * @returns new tag ibgib that has the ibgib related to it
 * @see {@link TAG_TARGET_REL8N_NAME}
 */
export async function rel8ToTag({ ibGib, addr, tagIbGib, metaspace, space, }) {
    const lc = `[${rel8ToTag.name}]`;
    try {
        if (logalot) {
            console.log(`${lc} starting... (I: b1fd25ec28bce8f1916b4ab55f48a724)`);
        }
        if (!addr && !ibGib) {
            throw new Error(`either addr or ibGib required (E: 3d580f8ecc251a0c81c7ea8bc3d38524)`);
        }
        addr ??= getIbGibAddr({ ibGib });
        if (addr !== getIbGibAddr({ ibGib })) {
            throw new Error(`addr (${addr}) differs from incoming ibGib's addr (${getIbGibAddr({ ibGib })}). (E: f2c14234a78c917fb9f587beaee89324)`);
        }
        const latestTagAddr = await metaspace.getLatestAddr({ ibGib: tagIbGib, space });
        if (latestTagAddr !== getIbGibAddr({ ibGib: tagIbGib })) {
            let resGetLatestTag = await metaspace.get({ addr: latestTagAddr, space });
            if (!resGetLatestTag.success || resGetLatestTag.ibGibs?.length !== 1) {
                throw new Error(`could not get latest tag (${latestTagAddr}) from space (${space.ib}). error: ${resGetLatestTag.errorMsg ?? '[unknown error (E: a4e31c98398b417db8f617f98a5f2741)]'} (E: 73c085d81efdab0e7b8939222ec07524)`);
            }
            tagIbGib = resGetLatestTag.ibGibs.at(0);
        }
        const rel8nsToAddByAddr = { [TAG_TARGET_REL8N_NAME]: [addr] };
        const resRel8ToTag = await rel8({ src: tagIbGib, rel8nsToAddByAddr, dna: true, nCounter: true });
        const newTagIbGib = resRel8ToTag.newIbGib;
        await metaspace.persistTransformResult({ resTransform: resRel8ToTag, space });
        await metaspace.registerNewIbGib({ ibGib: newTagIbGib, space });
        return newTagIbGib;
    }
    catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    }
    finally {
        if (logalot) {
            console.log(`${lc} complete.`);
        }
    }
}
//# sourceMappingURL=tag-helper.mjs.map