import { Injectable } from '@nestjs/common';
import { Tour } from '@prisma/client';

import { CalculationService } from 'src/modules/feat-calculation/calculation.service';
import { chunk } from 'src/utils';
import { TourPreStaging } from '../staging.interface';

@Injectable()
export class ToursCalculationAdapater {
  constructor(private readonly calculationService: CalculationService) {}

  public async addRevenueAndConsumptionCostsToTours(
    tours: TourPreStaging[],
  ): Promise<TourPreStaging[]> {
    const resultTours = [];
    for (const tourChunk of chunk(tours, 5)) {
      resultTours.push(
        await Promise.all(
          tourChunk.map((tour) =>
            this.addRevenueAndConsumptionCostsToTour(tour),
          ),
        ),
      );
    }
    return resultTours.flat();
  }

  public async addRevenueAndConsumptionCostsToTour(
    tour: TourPreStaging,
  ): Promise<TourPreStaging> {
    if (!tour?.ordinanceType) {
      return tour;
    }
    const revenue = await this.calculationService.calculateTourRevenue(
      tour as unknown as Tour,
    );
    const revenueDeviation =
      tour.revenueDispoLive > 0
        ? Math.round((revenue * 100) - (tour.revenueDispoLive * 100)) / 100
        : 0;

    const { consumptionCostsPerTour } =
      this.calculationService.getBillingInformationByOrdinanceType(
        tour.ordinanceType.match(/([A-Z])\w+/).at(0),
        tour.startDate,
      );

    return {
      ...tour,
      revenue,
      revenueDeviation,
      consumptionCosts: consumptionCostsPerTour,
    };
  }
}
