// src/services/ServiceRegistry.ts

import type { IInterfaceDescriptor } from '../engine/reflection/IInterfaceDescriptor';

export interface IServiceMeta {
  name: string;
  mount: string;
  iface?: IInterfaceDescriptor;
  tag?: string;
  metadata?: Record<string, unknown>;
}

export class ServiceRegistry {
  private services = new Map<string, IServiceMeta>();

  register(service: IServiceMeta): void {
    if (this.services.has(service.name)) {
      throw new Error(`[ServiceRegistry] Service '${service.name}' already registered`);
    }
    this.services.set(service.name, service);
  }

  unregister(name: string): boolean {
    return this.services.delete(name);
  }

  getByName(name: string): IServiceMeta | undefined {
    return this.services.get(name);
  }

  getByMount(mount: string): IServiceMeta | undefined {
    for (const service of this.services.values()) {
      if (service.mount === mount) return service;
    }
    return undefined;
  }

  getByTag(tag: string): IServiceMeta[] {
    const results: IServiceMeta[] = [];
    for (const service of this.services.values()) {
      if (service.tag === tag) results.push(service);
    }
    return results;
  }

  getByInterface(interfaceName: string): IServiceMeta[] {
    const results: IServiceMeta[] = [];
    for (const service of this.services.values()) {
      if (service.iface?.name === interfaceName) results.push(service);
    }
    return results;
  }

  listAll(): IServiceMeta[] {
    return Array.from(this.services.values());
  }

  has(name: string): boolean {
    return this.services.has(name);
  }

  clear(): void {
    this.services.clear();
  }

  get size(): number {
    return this.services.size;
  }
}
