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

@Pipe({
  name: 'currencyConvert',
  pure: false
})
export class CurrencyConvertPipe implements PipeTransform {
  private readonly langService = inject(LanguageService);
  private readonly ratesService = inject(CurrencyRatesService);

  private lastAmount: number | null = null;
  private lastFromCurrency = '';
  private lastTargetCurrency = '';
  private lastRatesVersion = -1;
  private lastResult = 0;

  transform(amount: number | null | undefined, fromCurrency: string | null | undefined): number {
    const value = amount ?? 0;
    const from = fromCurrency || this.ratesService.baseCurrency;
    const to = this.langService.currentCurrency();
    // Rates now load asynchronously and can update in place for a pair
    // already displayed - caching on (amount, from, to) alone means a price
    // rendered before its quote arrived would stay wrong forever, since
    // those three inputs never change again on their own. ratesVersion
    // forces a recompute whenever the underlying rate data changes.
    const ratesVersion = this.ratesService.ratesVersion();

    if (
      value === this.lastAmount &&
      from === this.lastFromCurrency &&
      to === this.lastTargetCurrency &&
      ratesVersion === this.lastRatesVersion
    ) {
      return this.lastResult;
    }

    this.lastAmount = value;
    this.lastFromCurrency = from;
    this.lastTargetCurrency = to;
    this.lastRatesVersion = ratesVersion;
    this.lastResult = this.ratesService.convert(value, from, to);

    return this.lastResult;
  }
}
