package com.iqser.red.service.persistence.management.v1.processor.service.persistence;

import java.time.OffsetDateTime;
import java.util.Optional;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.iqser.red.service.persistence.management.v1.processor.entity.configuration.AppVersionEntity;
import com.iqser.red.service.persistence.management.v1.processor.entity.configuration.AppVersionEntityKey;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.AppVersionRepository;

import jakarta.transaction.Transactional;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;

@Service
@Validated
@RequiredArgsConstructor
public class AppVersionPersistenceService {

    private final AppVersionRepository appVersionRepository;


    /**
     * Inserts a new AppVersionEntity if it does not already exist in the repository.
     *
     * @param appVersion          the version of the application, must not be blank
     * @param layoutParserVersion the version of the layout parser, must not be blank
     * @return {@code true} if the entity was inserted; {@code false} if it already exists
     * @throws ConstraintViolationException if the input parameters fail validation
     */
    @Transactional
    public boolean insertIfNotExists(@NotBlank String appVersion, @NotBlank String layoutParserVersion) throws ConstraintViolationException {

        AppVersionEntityKey key = new AppVersionEntityKey(appVersion, layoutParserVersion);
        if (!appVersionRepository.existsById(key)) {
            AppVersionEntity newAppVersion = new AppVersionEntity(appVersion, layoutParserVersion, OffsetDateTime.now());
            appVersionRepository.save(newAppVersion);
            return true;
        }
        return false;
    }


    /**
     * Retrieves the latest AppVersionEntity based on the date field.
     *
     * @return an Optional containing the latest AppVersionEntity if present, otherwise empty
     */
    public Optional<AppVersionEntity> getLatestAppVersion() {

        return appVersionRepository.findTopByOrderByDateDesc();
    }

}
