import { Injectable } from '@angular/core';
import { RegisteredWidget } from '../contracts/widget-component.contract';

@Injectable({ providedIn: 'root' })
export class WidgetRegistryService {
  private readonly widgets = new Map<string, RegisteredWidget>();

  register(widget: RegisteredWidget): void {
    this.widgets.set(this.toKey(widget.type, widget.version), widget);
  }

  registerMany(widgets: RegisteredWidget[]): void {
    for (const widget of widgets) {
      this.register(widget);
    }
  }

  resolve(type: string, version: string): RegisteredWidget | null {
    const exact = this.widgets.get(this.toKey(type, version));
    if (exact) {
      return exact;
    }

    const sameType = Array.from(this.widgets.values())
      .filter(widget => widget.type === type)
      .sort((a, b) => b.version.localeCompare(a.version));

    return sameType[0] ?? null;
  }

  list(): RegisteredWidget[] {
    return Array.from(this.widgets.values());
  }

  private toKey(type: string, version: string): string {
    return `${type}@${version}`;
  }
}
