/**
 * @module sync-peer-http-receiver-v1
 */
import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';
import { SyncPeer_V1 } from '../sync-peer-v1.mjs';
import { authenticateContextIntrinsically } from '../../sync-saga-context/sync-saga-context-helpers.mjs';
import { putInSpace, registerNewIbGib } from '../../../witness/space/space-helper.mjs';
const logalot = GLOBAL_LOG_A_LOT;
/**
 * Http Receiver Peer implementation.
 * Acts as the Symmetric Server Node. Accepts requests, routes to Receiver Coordinator.
 */
export class SyncPeerHttpReceiver_V1 extends SyncPeer_V1 {
    lc = `[${SyncPeerHttpReceiver_V1.name}]`;
    get classname() {
        return SyncPeerHttpReceiver_V1.name;
    }
    constructor(initialData, initialRel8ns) {
        super(initialData, initialRel8ns);
    }
    async preConnectCheck(opts) {
        const lc = `${this.lc}[${this.preConnectCheck.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 7cf8f805a31877fddf25b0ee09e49e26)`);
            }
            throw new Error(`not implemented (E: 4163e88d42f811da8b699cb6f7554a26)`);
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async connectImpl(opts) {
        const lc = `${this.lc}[${this.connectImpl.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 4c3d2a1b5f6e4d5c3b2a1b9c8d7e6f5a)`);
            }
            // Stub implementation for now.
            throw new Error(`not implemented (E: 48a5b8714d6861272510fc8c3cfef726)`);
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async postEstablishToReceiver({ newSenderIdentity, sessionIdentity, }) {
        const lc = `${this.lc}[${this.postEstablishToReceiver.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: f8d7c6b5a4e3d2c1b0a9f8e7d6c5b4a3)`);
            }
            throw new Error(`not implemented for HTTP receiver peer yet (E: a1b2c3d4e5f67890abcdef1234567890)`);
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async ensureLocalTempSpace() {
        const lc = `${this.lc}[${this.ensureLocalTempSpace.name}]`;
        try {
            if (!this.opts) {
                throw new Error(`opts not initialized. (E: 3a77d1f466b92cc7940c0f241ac6c926)`);
            }
            if (!this.opts.localTempSpace) {
                const { localMetaspace } = this.opts;
                const uuid = crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36);
                const tempSpaceName = `tmp_sync_recv_${uuid.substring(0, 8)}`;
                const localTempSpace = await localMetaspace.createNewLocalSpace({
                    opts: {
                        allowCancel: false,
                        spaceName: tempSpaceName,
                        getFnPrompt: localMetaspace.getFnPrompt,
                        logalot
                    }
                });
                if (!localTempSpace) {
                    throw new Error(`couldn't create a temp space (E: fed96e4491b7297240031fb7f04adf26)`);
                }
                await localTempSpace.initialized;
                this.opts.localTempSpace = localTempSpace;
            }
            return this.opts.localTempSpace;
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
    }
    async sendContextRequest(context) {
        const lc = `${this.lc}[${this.sendContextRequest.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 5297013216ae491894600b5a81115d26)`);
            }
            // This method might not be directly called on the receiver in the same way
            // as it is on the sender, or it handles the internal routing for the HTTP request.
            // When an HTTP Endpoint receives a POST, it deserializes the context and triggers this.
            throw new Error(`Not implemented (E: c56d5d6799b76bd8fd661846f6b9ee26)`);
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    /**
     * Entry point from the HTTP Endpoint Adapter (e.g. Express POST route)
     */
    async handleIncomingSyncRequest({ context, payloadIbGibsControl = [], }) {
        const lc = `${this.lc}[${this.handleIncomingSyncRequest.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 1de30d7db7e404ddf59eeed22a3bde26)`);
            }
            if (!this.opts) {
                throw new Error(`opts not initialized. (E: 56f585e25a54489280c9ba1393a46226)`);
            }
            const { localCoordinator, localMetaspace, localSpace } = this.opts;
            const localTempSpace = await this.ensureLocalTempSpace();
            // Put control ibgibs into durable space
            const allControlIbGibs = [context, ...payloadIbGibsControl];
            if (context.signedSessionIdentity) {
                allControlIbGibs.push(context.signedSessionIdentity);
            }
            for (const ibGib of allControlIbGibs) {
                await putInSpace({ space: localSpace, ibGibs: [ibGib] });
                await registerNewIbGib({ space: localSpace, ibGib });
            }
            // Auth verification (Bill architecture: turn-based context signing)
            const authErrors = await authenticateContextIntrinsically({
                context,
                space: localSpace,
            });
            if (authErrors.length > 0) {
                throw new Error(`Context authentication failed: ${authErrors.join(', ')} (E: d34b8ad97d84d1ba8d8f7facd288826)`);
            }
            // Put domain payloads into temp space
            if (context.payloadIbGibsDomain && context.payloadIbGibsDomain.length > 0) {
                for (const ibGib of context.payloadIbGibsDomain) {
                    await putInSpace({ space: localTempSpace, ibGibs: [ibGib] });
                }
            }
            const responseCtx = await localCoordinator.continueSync({
                sagaContext: context,
                metaspace: localMetaspace,
                mySpace: localSpace,
                myTempSpace: localTempSpace,
                peer: this,
            });
            return responseCtx || undefined;
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
}
//# sourceMappingURL=sync-peer-http-receiver-v1.mjs.map