/**
 * @module sync-peer-http-sender-v1
 */
import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
import { SyncPeer_V1 } from '../sync-peer-v1.mjs';
import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';
const logalot = GLOBAL_LOG_A_LOT;
/**
 * Http Sender Peer implementation.
 * Sends Context to a remote server utilizing POST for uplink and SSE for downlink.
 */
export class SyncPeerHttpSender_V1 extends SyncPeer_V1 {
    lc = `[${SyncPeerHttpSender_V1.name}]`;
    get classname() {
        return SyncPeerHttpSender_V1.name;
    }
    /**
     * Stored reference to the SSE EventSource connection.
     * Ensure you polyfill EventSource in Node environments if needed.
     */
    eventSource;
    constructor(initialData, initialRel8ns) {
        super(initialData, initialRel8ns);
    }
    preConnectCheck(opts) {
        const lc = `${this.lc}[${this.preConnectCheck.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 518718d0aa6830e182892b68fe2a2826)`);
            }
            throw new Error(`not implemented (E: 248be8a09b4dbd2fa820ef78258c5326)`);
        }
        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: ad84d8137351662fb8a30114a1fa4826)`);
            }
            throw new Error(`not implemented (E: 50752d5f4d188c45727d293549bffd26)`);
            // Stub implementation for now.
        }
        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: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c9b8)`);
            }
            throw new Error(`not implemented for HTTP sender peer yet (E: b1c2d3e4f5a67890abcdef1234567890)`);
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async sendContextRequest(context) {
        const lc = `${this.lc}[${this.sendContextRequest.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting...`);
            }
            if (!this.data?.syncEventsRoute) {
                throw new Error(`data.syncEventsRoute required. (E: 0338214dcd6fbe80f93a24e8a3df3226)`);
            }
            if (!this.data?.syncRoute) {
                throw new Error(`data.syncRoute required. (E: eda70809feb81c880c6accf83fc38826)`);
            }
            // 1. Establish SSE connection to `this.data.syncEventsRoute` if not already open
            //    (In a real implementation, you might initialize this elsewhere or ensure it stays reconnecting)
            if (!this.eventSource) {
                if (logalot) {
                    console.log(`${lc} initializing EventSource to ${this.data.syncEventsRoute}`);
                }
                this.eventSource = new EventSource(this.data.syncEventsRoute);
                this.eventSource.onerror = (err) => console.error(`${lc} EventSource error:`, err);
            }
            return new Promise(async (resolve, reject) => {
                // 2. Setup listeners for SSE incoming context and ibgib payloads
                const onMessage = async (event) => {
                    try {
                        const parsedData = JSON.parse(event.data);
                        // TODO [USER]: Determine if `parsedData` is a domain payload ibGib OR the final response context.
                        // e.g.:
                        // if (parsedData.isDomainIbGib) {
                        //     // Deserialize to IbGib_V1
                        //     const ibGib = parsedData;
                        //     await this.payloadIbGibsDomainReceived$.next(ibGib);
                        // } else if (parsedData.isResponseContext) {
                        //     // Deserialize to SyncSagaContextIbGib_V1
                        //     const responseContext = parsedData;
                        //     this.eventSource?.removeEventListener('message', onMessage);
                        //     resolve(responseContext);
                        // }
                    }
                    catch (e) {
                        console.error(`${lc} failed to parse SSE message`, e);
                    }
                };
                this.eventSource.addEventListener('message', onMessage);
                try {
                    // 3. Serialize Context and Control IbGibs
                    // TODO [USER]: Serialize the `context` and `controlIbGibs` into your wire format
                    const payloadBody = JSON.stringify({
                        context: context,
                        // controlIbGibs: ...
                    });
                    // 4. POST the context to `this.data.syncRoute`
                    if (!this.data) {
                        throw new Error(`(UNEXPECTED) this.data falsy? (E: 8c6aa9e1aa7869465a26ee3a7d136826)`);
                    }
                    const response = await fetch(this.data.syncRoute, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            // Add Authorization headers here if needed
                        },
                        body: payloadBody,
                    });
                    if (!response.ok) {
                        throw new Error(`HTTP Sync Error: ${response.status} ${await response.text()} (E: f086e8ae65780182b894f638933ca826)`);
                    }
                    // 5. Wait for the SSE stream response to resolve with the responseContext
                    // The Promise will remain pending until `onMessage` identifies the final response context and calls resolve().
                }
                catch (e) {
                    this.eventSource?.removeEventListener('message', onMessage);
                    reject(e);
                }
            });
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
}
//# sourceMappingURL=sync-peer-http-sender-v1.mjs.map