import { Injectable } from '@nestjs/common';
import { format } from 'date-fns';
import { TourService } from '../feat-business-objects/entities/tour/tour.service';
import { CalculationService } from '../feat-calculation/calculation.service';
import { TourCostBreakdownObjectType } from './accounting.object-type';

@Injectable()
export class AccountingService {
  constructor(
    private readonly calculation: CalculationService,
    private readonly tourService: TourService,
  ) {}

  async tourCostBreakdown(
    operationId: string,
  ): Promise<TourCostBreakdownObjectType> {
    const tour = await this.tourService.findByOperationId(operationId);

    const { tariff, servicePositions } =
      await this.calculation.listProvidedServicePositions(tour);

    if (!tariff || servicePositions.length === 0) {
      return {
        tariffDescription: '!-- Tarif kann nicht ermittelt werden --!',
        tariffValidityPeriod: '--',
        servicePositions: [],
      };
    }

    return {
      tariffDescription: tariff.tariffGroup?.description,
      tariffValidityPeriod: this.formatTariffValidityPeriod(
        tariff.validFrom,
        tariff.validTo,
      ),
      servicePositions: servicePositions.map(([costType, value]) => ({
        value,
        variant: costType.variant,
        description: costType.description,
      })),
    };
  }

  private formatTariffValidityPeriod(from: Date, to?: Date): string {
    if (!to) return `ab ${format(new Date(from), 'yyyy-MM-dd')}`;
    return `${format(new Date(from), 'yyyy-MM-dd')} - ${format(new Date(to), 'yyyy-MM-dd')}`;
  }
}
