import { Injector, ProviderToken, Type } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { bootstrapCrtModule } from '@creatio-devkit/common';
import { RuntimeFeatureModule } from './runtime-feature.module';
import { RatingComponent } from './view-elements/rating/rating.component';
import { RATING_SELECTOR } from './runtime-feature.ids';
import { ensureFeatureModuleRef } from '../../remote-app-context';

function defineCustomElement(selector: string, component: Type<unknown>, injector: Injector): void {
  if (!customElements.get(selector)) {
    customElements.define(selector, createCustomElement(component, { injector }));
  }
}

/**
 * Initializes the runtime feature module and boots the Creatio runtime integration.
 */
export async function activateRuntimeFeature(): Promise<void> {
  const moduleRef = await ensureFeatureModuleRef(RuntimeFeatureModule);

  defineCustomElement(RATING_SELECTOR, RatingComponent, moduleRef.injector);

  bootstrapCrtModule('sdk_custom_component_ai', RuntimeFeatureModule, {
    resolveDependency: (token: unknown) => moduleRef.injector.get(token as ProviderToken<unknown>),
  });
}
