/**
 * @module sync saga context helpers
 */
import { extractErrorMsg, getTimestamp } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
import { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs';
import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
import { SYNC_SAGA_CONTEXT_ATOM } from './sync-saga-context-constants.mjs';
import { SYNC_SAGA_PAYLOAD_ADDRS_DOMAIN } from '../sync-constants.mjs';
/**
 * Constructs the standard 'ib' string for a Sync Saga Context stone.
 */
export async function getSyncSagaContextIb({ data, }) {
    const lc = `[${getSyncSagaContextIb.name}]`;
    try {
        if (!data) {
            throw new Error(`data required (E: 839d82138c234b3e89582855594191fe)`);
        }
        const payloadCount = data['@payloadAddrsDomain'] ? data['@payloadAddrsDomain'].length : 0;
        // sync_sagacontext cmd
        const ib = [
            SYNC_SAGA_CONTEXT_ATOM,
            payloadCount,
        ].join(' ');
        return ib;
    }
    catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    }
}
/**
 * Parses a standard Sync Saga Context 'ib' string.
 */
export async function parseSyncSagaContextIb({ ib, }) {
    const lc = `[${parseSyncSagaContextIb.name}]`;
    try {
        const parts = ib.split(' ');
        if (parts.length !== 2) {
            throw new Error(`Invalid sync saga context ib. Expected at least 2 parts [atom, payloadCount]. Got ${parts.length}. (E: 8b06c88820c74f5fb9f21f148459422a)`);
        }
        const [atom, payloadCountStr,] = parts;
        if (atom !== SYNC_SAGA_CONTEXT_ATOM) {
            throw new Error(`Atom mismatch. Expected ${SYNC_SAGA_CONTEXT_ATOM}. Got ${atom}. (E: 67d71fc0f8d04840b178652309f471f5)`);
        }
        if (!payloadCountStr) {
            throw new Error(`invalid ib. second piece should be payloadCount but is falsy (E: 0bb7580793d800ca02227828a7294826)`);
        }
        const payloadCount = parseInt(payloadCountStr);
        if (isNaN(payloadCount)) {
            throw new Error(`payloadCountStr is not a number. (E: 49457814282a44069871630987588722)`);
        }
        return { atom, payloadCount };
    }
    catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    }
}
/**
 * Creates a new SyncSagaContext ibGib stone.
 *
 * @returns The context ibGib.
 */
export async function createSyncSagaContext({ sagaFrame, sessionKeystones, payloadIbGibsDomain, }) {
    const date = new Date();
    const timestamp = getTimestamp(date);
    const timestampMs = date.getMilliseconds();
    const data = {
        timestamp,
        timestampMs,
    };
    // Domain Payloads 
    const payloadAddrsDomain = payloadIbGibsDomain ? payloadIbGibsDomain?.map(x => getIbGibAddr({ ibGib: x })) : undefined;
    if (payloadAddrsDomain && payloadAddrsDomain.length > 0) {
        data[SYNC_SAGA_PAYLOAD_ADDRS_DOMAIN] = payloadAddrsDomain;
    }
    // rel8ns should always have saga frame, sometimes have keystone
    const rel8ns = {
        sagaFrame: [getIbGibAddr({ ibGib: sagaFrame })],
    };
    if (sessionKeystones && sessionKeystones.length > 0) {
        rel8ns.sessionKeystone = sessionKeystones.map(x => getIbGibAddr({ ibGib: x }));
    }
    // Generate standard ib
    const ib = await getSyncSagaContextIb({ data });
    const contextIbGib = await Factory_V1.stone({
        parentPrimitiveIb: SYNC_SAGA_CONTEXT_ATOM,
        ib,
        data,
        rel8ns,
    });
    // Attach actual ibgibs for transport 
    if (payloadIbGibsDomain && payloadIbGibsDomain.length > 0) {
        contextIbGib.payloadIbGibsDomain = payloadIbGibsDomain;
    }
    return contextIbGib;
}
//# sourceMappingURL=sync-saga-context-helpers.mjs.map