package eu.dnetlib.organizations.repository;

import java.time.OffsetDateTime;
import java.util.List;

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

import eu.dnetlib.organizations.model.OpenaireDuplicate;
import eu.dnetlib.organizations.model.OpenaireDuplicatePK;

@Repository
public interface OpenaireDuplicateRepository extends JpaRepository<OpenaireDuplicate, OpenaireDuplicatePK> {

	List<OpenaireDuplicate> findByLocalId(String localId);

	@Modifying
	@Query(value = "update oa_duplicates set modified_by = ?3, modification_date = ?4 where (local_id = ?1 and oa_original_id = ?2) or (local_id = ?2 and oa_original_id = ?1)", nativeQuery = true)
	void updateModificationDate(String id1, String id2, String user, OffsetDateTime now);

	@Modifying
	@Query(value = "update oa_duplicates set created_by = ?3 where ((local_id = ?1 and oa_original_id = ?2) or (local_id = ?2 and oa_original_id = ?1)) and (created_by is null or created_by = '')", nativeQuery = true)
	void updateCreatedByIfMissing(String id1, String id2, String user);

	List<OpenaireDuplicate> findByOaOriginalId(String oaOriginalId);

}
