import { isDevMode, Pipe, PipeTransform, inject } from '@angular/core';

import { DevLogService } from '../devtools/dev-log.service';
import { TELEMETRY_EVENT_TYPE_LABELS } from './telemetry-event-type-labels.config';

@Pipe({
  name: 'telemetryEventType',
  standalone: true,
})
export class TelemetryEventTypePipe implements PipeTransform {
  private readonly devLog = inject(DevLogService);
  private readonly warnedUnknown = new Set<string>();

  transform(value: unknown): string {
    if (value == null || value === '') {
      return '—';
    }
    const raw = typeof value === 'string' ? value : String(value);
    const trimmed = raw.trim();
    if (trimmed === '') {
      return '—';
    }
    const lookup = trimmed.toLowerCase();
    const mapped = TELEMETRY_EVENT_TYPE_LABELS[lookup];
    if (mapped !== undefined && String(mapped).trim() !== '') {
      return String(mapped).trim();
    }
    if (isDevMode() && !this.warnedUnknown.has(lookup)) {
      this.warnedUnknown.add(lookup);
      this.devLog.add({
        level: 'warn',
        source: 'system',
        message: `Неизвестный тип события телеметрии (нет подписи в telemetry-event-type-labels.config): ${trimmed}`,
      });
    }
    return trimmed;
  }
}
