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

import java.util.List;

import jakarta.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import com.iqser.red.service.persistence.management.v1.processor.entity.configuration.DictionaryEntryEntity;

public interface EntryRepository extends EntryRepositoryCustom, JpaRepository<DictionaryEntryEntity, Long> {

    @Modifying
    @Query("update DictionaryEntryEntity e set e.version = :version where e.typeId = :typeId  and e.deleted = false")
    void updateVersionWhereTypeId(long version, String typeId);


    @Modifying
    @Query("update DictionaryEntryEntity e set e.typeId = :newTypeId, e.version = e.version + 1 where e.typeId =:typeId and e.deleted = false")
    void updateTypeIdAndIncrementVersionByOne(String typeId, String newTypeId);


    List<DictionaryEntryEntity> findByTypeIdAndVersionGreaterThan(String typeId, long version);


    List<DictionaryEntryEntity> findByTypeIdContainsAndValue(String typeId, String value);


    @Modifying(flushAutomatically = true, clearAutomatically = true)
    @Transactional
    @Query("update DictionaryEntryEntity e set e.deleted = true, e.version = :version where e.typeId = :typeId")
    void deleteAllEntriesForTypeId(String typeId, long version);


    @Modifying(flushAutomatically = true, clearAutomatically = true)
    @Transactional
    @Query(value = "insert into dictionary_entry (value, version, deleted, type_id) " + " select value, 1, false, :newTypeId from dictionary_entry where type_id = :originalTypeId and deleted = false", nativeQuery = true)
    void cloneEntries(String originalTypeId, String newTypeId);

}
