package llc.arma.fleet.monitor.data.repository

import llc.arma.fleet.monitor.data.entity.UserEntity
import llc.arma.fleet.monitor.data.entity.UserRole
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.Query
import org.springframework.data.repository.query.Param

interface UserRepository : JpaRepository<UserEntity, Long> {
    fun findByLogin(login: String): UserEntity?
    fun findByEmail(email: String): UserEntity?
    fun findByLoginOrEmail(login: String, email: String): UserEntity?
    fun existsByLogin(login: String): Boolean
    fun existsByEmail(email: String): Boolean
    fun existsByLoginAndIdNot(login: String, id: Long): Boolean
    fun existsByEmailAndIdNot(email: String, id: Long): Boolean

    @Query(
        """
        select user from UserEntity user
        where (
            lower(user.lastName) like lower(concat('%', :query, '%'))
            or lower(user.firstName) like lower(concat('%', :query, '%'))
            or lower(user.email) like lower(concat('%', :query, '%'))
            or lower(user.login) like lower(concat('%', :query, '%'))
        )
        """,
    )
    fun findByLastNameContainingIgnoreCaseOrFirstNameContainingIgnoreCaseOrEmailContainingIgnoreCaseOrLoginContainingIgnoreCase(
        @Param("query") query: String,
        pageable: Pageable,
    ): Page<UserEntity>

    fun findByRoleIn(
        roles: List<UserRole>,
        pageable: Pageable,
    ): Page<UserEntity>

    @Query(
        """
        select user from UserEntity user
        where user.role in :roles
          and (
            lower(user.lastName) like lower(concat('%', :query, '%'))
            or lower(user.firstName) like lower(concat('%', :query, '%'))
            or lower(user.email) like lower(concat('%', :query, '%'))
            or lower(user.login) like lower(concat('%', :query, '%'))
          )
        """,
    )
    fun searchByQueryAndRoleIn(
        @Param("query") query: String,
        @Param("roles") roles: List<UserRole>,
        pageable: Pageable,
    ): Page<UserEntity>
}
