package de.avatic.lcc.service.configuration;

import de.avatic.lcc.repositories.country.CountryPropertyRepository;
import de.avatic.lcc.repositories.properties.PropertyRepository;
import de.avatic.lcc.repositories.properties.PropertySetRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * A service class responsible for managing staged changes to properties.
 * It provides functionalities to check for property drafts and apply them
 * when necessary.
 */
@Service
public class PropertyApprovalService {
    private final PropertySetRepository propertySetRepository;
    private final PropertyRepository propertyRepository;
    private final CountryPropertyRepository countryPropertyRepository;


    /**
     * Constructs a new {@code PropertyStagedChangesService} with the required repositories.
     *
     * @param propertySetRepository     the repository for managing property sets
     * @param propertyRepository        the repository for managing properties
     * @param countryPropertyRepository the repository for managing country-specific properties
     */
    public PropertyApprovalService(PropertySetRepository propertySetRepository, PropertyRepository propertyRepository, CountryPropertyRepository countryPropertyRepository) {
        this.propertySetRepository = propertySetRepository;
        this.propertyRepository = propertyRepository;
        this.countryPropertyRepository = countryPropertyRepository;
    }

    /**
     * Checks if there are any staged (draft) properties that have not yet been applied.
     *
     * @return {@code true} if there are property drafts, {@code false} otherwise
     */
    public Boolean hasPropertiesDraft() {
        return propertySetRepository.hasPropertiesDraft();
    }

    /**
     * Applies all staged (draft) properties if there are any present.
     * This method is transactional to ensure that all changes are applied atomically.
     */
    @Transactional
    public void applyDraft() {
        if(!propertySetRepository.hasPropertiesDraft()) return;
        Integer setId = propertySetRepository.getDraftSetId();
        countryPropertyRepository.fillDraft(setId);
        propertyRepository.fillDraft(setId);
        propertySetRepository.applyDraft();
    }

}
