// src/engine/core/Lifecycle.ts

import type { IMatrixContext } from './IMatrixContext';
import { TopicRouter } from '../messaging/TopicRouter';
import type { MxEnvelope } from '../messaging/MxEnvelope';
import type { TransportHandler } from '../remoting/ITransportAdapter';

/**
 * Convenience helpers for lifecycle topics (available/removed).
 */
export class Lifecycle {
  /** Subscribe once to lifecycle.available for a given mount via $events. */
  static onFirstAvailable(
    context: IMatrixContext,
    mount: string,
    handler: TransportHandler
  ): () => void {
    const transport = context.transport;
    const eventsTopic = TopicRouter.events(mount);

    let off: () => void = () => {};
    off = transport.subscribe(eventsTopic, (payload, meta) => {
      const envelope = payload as MxEnvelope;
      if (envelope?.op === 'lifecycle.available') {
        off();
        handler(envelope.payload, meta);
      }
    });
    return off;
  }

  /** Subscribe to lifecycle.removed for a given mount via $events. */
  static onRemoved(
    context: IMatrixContext,
    mount: string,
    handler: TransportHandler
  ): () => void {
    const transport = context.transport;
    const eventsTopic = TopicRouter.events(mount);
    return transport.subscribe(eventsTopic, (payload, meta) => {
      const envelope = payload as MxEnvelope;
      if (envelope?.op === 'lifecycle.removed') {
        handler(envelope.payload, meta);
      }
    });
  }
}
