import type { BaseIntegration } from './classes.baseintegration.js';
import type { IIntegrationRuntime, IIntegrationSetupContext } from './types.js';

export class IntegrationRuntimeManager {
  private readonly runtimes = new Map<string, IIntegrationRuntime>();

  public async setupIntegration<TConfig>(
    integrationArg: BaseIntegration<TConfig>,
    configArg: TConfig,
    contextArg: IIntegrationSetupContext = {}
  ): Promise<IIntegrationRuntime> {
    const runtime = await integrationArg.setup(configArg, contextArg);
    this.runtimes.set(integrationArg.domain, runtime);
    return runtime;
  }

  public getRuntime(domainArg: string): IIntegrationRuntime | undefined {
    return this.runtimes.get(domainArg);
  }

  public listRuntimes(): IIntegrationRuntime[] {
    return [...this.runtimes.values()];
  }

  public async destroyAll(): Promise<void> {
    for (const runtime of this.runtimes.values()) {
      await runtime.destroy();
    }
    this.runtimes.clear();
  }
}
