package de.avatic.lcc.service.access;

import de.avatic.lcc.dto.generic.ValidityPeriodDTO;
import de.avatic.lcc.repositories.calculation.CalculationJobRepository;
import de.avatic.lcc.repositories.rates.ValidityPeriodRepository;
import de.avatic.lcc.service.transformer.rates.ValidityPeriodTransformer;
import de.avatic.lcc.util.exception.badrequest.NotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Service class responsible for managing validity periods in the system.
 * <p>
 * This service provides operations for retrieving and manipulating validity periods,
 * acting as an intermediary between the repository layer and the application layer.
 * It uses a transformer to convert between entity and DTO representations.
 * </p>
 *
 */
@Service
public class ValidityPeriodService {

    private final ValidityPeriodRepository validityPeriodRepository;
    private final ValidityPeriodTransformer validityPeriodTransformer;
    private final CalculationJobRepository calculationJobRepository;

    /**
     * Constructs a new ValidityPeriodService with the required dependencies.
     *
     * @param validityPeriodRepository Repository for accessing validity period data
     * @param validityPeriodTransformer Transformer for converting between entity and DTO representations
     */
    public ValidityPeriodService(ValidityPeriodRepository validityPeriodRepository, ValidityPeriodTransformer validityPeriodTransformer, CalculationJobRepository calculationJobRepository) {
        this.validityPeriodRepository = validityPeriodRepository;
        this.validityPeriodTransformer = validityPeriodTransformer;
        this.calculationJobRepository = calculationJobRepository;
    }


    /**
     * Retrieves all validity periods from the repository and transforms them to DTOs.
     * <p>
     * Fetches the list of validity periods from the repository and transforms each entity
     * to its corresponding DTO representation using the transformer.
     * </p>
     *
     * @return A list of {@link ValidityPeriodDTO} objects representing all validity periods
     */
    public List<ValidityPeriodDTO> listPeriods() {
        return validityPeriodRepository.listPeriods().stream().map(validityPeriodTransformer::toValidityPeriodDTO).toList();
    }

    /**
     * Invalidates a validity period with the specified ID.
     * <p>
     * Marks the validity period as invalid in the repository based on its ID.
     * </p>
     *
     * @param id The unique identifier of the validity period to invalidate
     */
    public void invalidate(Integer id) {
        if (!validityPeriodRepository.invalidateById(id))
            throw new NotFoundException(NotFoundException.NotFoundType.EXPIRED_VALIDITY_PERIOD, "id", id.toString());

        calculationJobRepository.invalidateByPeriodId(id);
    }
}
