import { Injectable } from '@angular/core';
import { Observable, map, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { CategoriesWidgetComponent, FooterNavigationWidgetComponent, HeroWidgetComponent, ProductCarouselWidgetComponent, RecentlyViewedWidgetComponent } from '../ui';
import { RegisteredWidget } from '../contracts/widget-component.contract';
import { WidgetRegistryService } from './widget-registry.service';
import { WidgetManifestService } from './widget-manifest.service';

const APPROVED_WIDGET_COMPONENTS: Record<string, RegisteredWidget['component']> = {
  'hero': HeroWidgetComponent,
  'categories': CategoriesWidgetComponent,
  'footer': FooterNavigationWidgetComponent,
  'footer-navigation': FooterNavigationWidgetComponent,
  'product-carousel': ProductCarouselWidgetComponent,
  'product-collection': ProductCarouselWidgetComponent,
  'recently-viewed': RecentlyViewedWidgetComponent
};

@Injectable({ providedIn: 'root' })
export class WidgetRegistryBootstrapService {
  constructor(
    private readonly registry: WidgetRegistryService,
    private readonly widgetManifest: WidgetManifestService
  ) {}

  registerFromManifest(): Observable<void> {
    return this.widgetManifest.getWidgets().pipe(
      map((manifestWidgets) => {
        const widgets = manifestWidgets
          .filter((item) => item.enabled !== false)
          .map((item): RegisteredWidget | null => {
            const component = APPROVED_WIDGET_COMPONENTS[item.componentKey];
            if (!component) {
              return null;
            }

            return {
              type: item.type,
              version: item.version,
              component
            };
          })
          .filter((item): item is RegisteredWidget => item !== null);

        this.registry.registerMany(widgets);
      }),
      catchError(() => of(undefined))
    );
  }
}
