import { IPriceCyclesModel } from '@fleio-api/plugins/domains/model/price-cycle.model';

export class PriceValidator {
  static maxDiscountedRatio = 0.5;

  static validatePrices(prices: IPriceCyclesModel, transferAddsYears = true): string[] {
    const errors: string[] = [];
    const firstPriceValue = prices.prices_per_years[0];

    if (prices.price_type === 'transfer' && !transferAddsYears) {
      // other years do not matter when transfer does not add years
      return errors;
    }

    let hasAtLeastOnePriceDefined = typeof firstPriceValue === 'number';
    for (let index = 1; index < 10; index++) {
      const previousPrice = prices.prices_per_years[index - 1];
      const currentPrice = prices.prices_per_years[index];
      const years = index + 1;
      const oneYearPrice = currentPrice / years;
      if (typeof currentPrice !== 'number') {
        continue;
      }
      hasAtLeastOnePriceDefined = true;
      if (currentPrice < previousPrice) {
        errors.push($localize`${prices.price_type_display} price (${prices.currency.code}): Price for ${years} years is lower than price for ${years - 1}`);
        continue;
      }
      if (typeof firstPriceValue === 'number' && firstPriceValue * PriceValidator.maxDiscountedRatio > oneYearPrice) {
        errors.push($localize`${prices.price_type_display} price (${prices.currency.code}): Price for ${years} years seems too low compared to one year price`);
      }
    }

    if (!hasAtLeastOnePriceDefined) {
      errors.push($localize`${prices.price_type_display} price (${prices.currency.code}): None of the price fields are filled in.`);
    }

    return errors;
  }

  static hasNegativePrices(prices: IPriceCyclesModel): boolean {
    for (const price of prices.prices_per_years) {
      if (price < 0) {
        return true;
      }
    }

    return false;
  }
}
