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

import java.util.Comparator;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iqser.red.service.persistence.management.v1.processor.entity.migration.MigrationEntity;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.MigrationRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class MigrationPersistenceService {

    private final MigrationRepository migrationRepository;


    @Transactional
    public void insertMigration(String name, long version) {

        migrationRepository.save(MigrationEntity.builder().name(name).version(version).build());
    }


    public boolean isProcessed(long version, long lastProcessedVersion) {

        var migrations = migrationRepository.findByVersionGreaterThan(lastProcessedVersion);
        if (migrations == null || migrations.isEmpty()) {
            return version <= lastProcessedVersion;
        }

        return migrations.stream().anyMatch(m -> m.getVersion() == version);
    }


    public Long getLatestProcessedVersion() {

        var migrations = migrationRepository.findAll();
        if (migrations.isEmpty()) {
            return null;
        }
        return migrations.stream().sorted(Comparator.comparing(MigrationEntity::getVersion).reversed()).collect(Collectors.toList()).get(0).getVersion();
    }

}
