/**
 * @module sync-innerspace-dest-ahead.respec
 *
 * Verifies Complex Sync Scenarios using InnerSpace.
 */
import { respecfully, iReckon, ifWeMight } from '@ibgib/helper-gib/dist/respec-gib/respec-gib.mjs';
const maam = `[${import.meta.url}]`, sir = maam;
import { delay } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
import { SyncSagaCoordinator } from './sync-saga-coordinator.mjs';
import { putInSpace, getFromSpace } from '../witness/space/space-helper.mjs';
import { Metaspace_Innerspace } from '../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace.mjs';
import { InnerSpace_V1 } from '../witness/space/inner-space/inner-space-v1.mjs';
import { createTimelineRootHelper, getTestKeystoneServiceHelper } from '../agent-helpers.mjs';
import { mut8Timeline } from '../timeline/timeline-api.mjs';
import { DEFAULT_INNER_SPACE_DATA_V1 } from '../witness/space/inner-space/inner-space-types.mjs';
import { SyncPeerInnerspace_V1 } from './sync-peer/sync-peer-innerspace/sync-peer-innerspace-v1.mjs';
const logalot = true;
const lc = `[sync-innerspace-dest-ahead.respec]`;
await respecfully(sir, `Sync InnerSpaces (Dest Ahead)`, async () => {
    let metaspace;
    let sourceSpace;
    let destSpace;
    await respecfully(sir, `Dest Ahead (Remote Newer)`, async () => {
        // 1. Setup Spaces
        metaspace = new Metaspace_Innerspace(undefined);
        await metaspace.initialize({
            getFnAlert: () => async ({ title, msg }) => { },
            getFnPrompt: () => async ({ title, msg }) => { return ''; },
            getFnPromptPassword: () => async (title, msg) => { return null; },
        });
        while (!metaspace.initialized) {
            await delay(10);
        }
        const defaultLocalUserSpace = await metaspace.getLocalUserSpace({ lock: false });
        await defaultLocalUserSpace.initialized;
        sourceSpace = new InnerSpace_V1({
            ...DEFAULT_INNER_SPACE_DATA_V1,
            name: 'source',
            uuid: 'source_uuid',
            description: 'source test space',
        });
        await sourceSpace.initialized;
        destSpace = new InnerSpace_V1({
            ...DEFAULT_INNER_SPACE_DATA_V1,
            name: 'dest',
            uuid: 'dest_uuid',
            description: 'dest test space',
        });
        await destSpace.initialized;
        // 2. Seed Data
        // Root -> V1 (Shared) -> V2 (Dest has New)
        // Source only has V1.
        const root = await createTimelineRootHelper({
            ib: 'timeline_root_ff',
            data: { type: 'root', label: 'Root' },
            space: sourceSpace,
        });
        // V1 (Both have it, but we create in source and copy to dest)
        const v1 = await mut8Timeline({
            timeline: root,
            mut8Opts: { dataToAddOrPatch: { type: 'comment', label: 'V1' } },
            metaspace,
            space: sourceSpace,
        });
        // Transfer Root & V1 to Dest
        await putInSpace({ space: destSpace, ibGibs: [root, v1] }); // Naive seeding
        // V2 (Created in Dest ONLY)
        const v2 = await mut8Timeline({
            timeline: v1, // v1 is in memory, linked to source, but we want to Mutate IN DEST SPACE
            mut8Opts: { dataToAddOrPatch: { type: 'comment', label: 'V2' } },
            metaspace,
            space: destSpace, // Mutate in Dest
        });
        const addrV2 = getIbGibAddr({ ibGib: v2 });
        await ifWeMight(sir, 'verify setup', async () => {
            // Ensure V2 is ONLY in Dest (it is, per `space: destSpace`)
            // Ensure Source does NOT have V2
            const checkV2InSource = await getFromSpace({ space: sourceSpace, addr: addrV2 });
            iReckon(sir, checkV2InSource.success && !!checkV2InSource.ibGibs?.length).asTo('Source has V2').isGonnaBeFalse();
        });
        // 3. Setup Sync
        const mockKeystone = await getTestKeystoneServiceHelper();
        const senderCoordinator = new SyncSagaCoordinator(mockKeystone);
        const receiverCoordinator = new SyncSagaCoordinator(mockKeystone);
        const peer = new SyncPeerInnerspace_V1({
            senderSpace: sourceSpace,
            receiverSpace: destSpace,
            receiverCoordinator: receiverCoordinator,
            receiverMetaspace: metaspace,
            receiverTempSpace: 0, // this is wrong just getting to build
            senderTempSpace: 0, // this is wrong just getting to build
        }, {
            classname: SyncPeerInnerspace_V1.name
        });
        // 4. Run Sync (Source Pushes V1)
        console.log(`${lc} Running Sync...`);
        const resSync = await senderCoordinator.sync({
            peer: peer,
            localSpace: sourceSpace,
            metaspace: metaspace,
            domainIbGibs: [v1], // Source tries to push V1
            useSessionIdentity: false,
        });
        await resSync.done;
        // 5. Verify Dest (Should still have V2 as latest)
        console.log(`${lc} Verifying Destination...`);
        await ifWeMight(sir, `verify dest stays ahead`, async () => {
            // Verify Tip (V2)
            const getV2 = await getFromSpace({ space: destSpace, addr: addrV2 });
            iReckon(sir, getV2.success).asTo('V2 still present in Dest').isGonnaBeTrue();
            // Verify V2 points to V1
            const v2IbGib = getV2.ibGibs[0];
            const pastAddr = v2IbGib.rel8ns?.past?.at(-1);
            iReckon(sir, pastAddr === getIbGibAddr({ ibGib: v1 })).asTo('V2 points to V1').isGonnaBeTrue();
        });
    });
});
//# sourceMappingURL=sync-innerspace-dest-ahead.respec.mjs.map