import { Pipe, PipeTransform, inject } from '@angular/core';
import { LanguageService } from '../services/language.service';

@Pipe({
  name: 'langRoute',
  pure: false
})
export class LangRoutePipe implements PipeTransform {
  private langService = inject(LanguageService);
  private lastLang = '';
  private lastInput: unknown = null;
  private lastResult: string | (string | number)[] = '';

  transform(value: string | (string | number)[]): string | (string | number)[] {
    const lang = this.langService.currentLanguage();

    // Short-circuit if nothing changed
    if (lang === this.lastLang && value === this.lastInput) {
      return this.lastResult;
    }

    this.lastLang = lang;
    this.lastInput = value;

    if (typeof value === 'string') {
      this.lastResult = value === '/' ? `/${lang}` : `/${lang}${value}`;
    } else if (Array.isArray(value) && value.length > 0) {
      const [first, ...rest] = value;
      this.lastResult = [`/${lang}${first}`, ...rest];
    } else {
      this.lastResult = value;
    }

    return this.lastResult;
  }
}
