package com.izouma.nineth.repo;

import com.izouma.nineth.domain.IdentityAuth;
import com.izouma.nineth.enums.AuthStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

public interface IdentityAuthRepo extends JpaRepository<IdentityAuth, Long>, JpaSpecificationExecutor<IdentityAuth> {
    @Query("update IdentityAuth t set t.del = true where t.id = ?1")
    @Modifying
    @Transactional
    void softDelete(Long id);

    @Query("update IdentityAuth t set t.del = true where t.userId = ?1")
    @Modifying
    @Transactional
    void softDeleteByUserId(Long userId);

    List<IdentityAuth> findByUserIdAndDelFalse(Long userId);

    List<IdentityAuth> findByUserId(Long userId);

    Optional<IdentityAuth> findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(Long userId, AuthStatus status);

    Optional<IdentityAuth> findByIdAndDelFalse(Long id);

    List<IdentityAuth> findAllByIdNoAndUserIdIsNotAndDelFalse(String idNo, Long userId);

    List<IdentityAuth> findByStatusAndAutoValidated(AuthStatus status, boolean validated);

    int countByIdNoAndStatus(String idNo, AuthStatus status);

    @Query("select distinct i.userId from IdentityAuth i")
    Page<Long> listUserId(Pageable pageable);

    @Query("delete from IdentityAuth i where i.userId = ?1 and i.id <> ?2")
    @Modifying
    @Transactional
    int deleteDuplicated(Long userId, Long id);

    List<IdentityAuth> findByUserIdInAndStatus(Iterable<Long> userId, AuthStatus status);

    IdentityAuth findFirstByUserId(Long userId);
}