package com.kospo.talk.repository;

import com.kospo.talk.model.SmUser;
import com.kospo.talk.model.SmUserId;
import com.kospo.talk.payload.ISmUserDto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface SmUserRepository extends JpaRepository<SmUser, SmUserId> {

    List<SmUser> findAll();

    List<SmUser> findByIdWorkId(String workId);

    List<SmUser> findByIdSabun(String sabun);

    @Query(value="select sm_user.*, users.online_yn\n" +
            "from sm_user\n" +
            " inner join users on sm_user.sabun = users.sabun\n" +
            "and work_id in (select work_id\n" +
            "                  from sm_user\n" +
            "                  where sabun = :sabun)", nativeQuery = true)
    List<ISmUserDto> findBySmUserInSabun(@Param("sabun") String sabun);


    @Query(value="select sm_user.work_id, sm_user.sabun, cast(max(cast(users.online_yn as integer)) as boolean) as online_yn\n" +
            "from sm_user\n" +
            " inner join users on sm_user.sabun = users.sabun\n" +
            "and work_id in (select work_id\n" +
            "                  from sm_user\n" +
            "                  where sabun = :sabun)\n" +
            "group by sm_user.work_id, sm_user.sabun order by sm_user.work_id", nativeQuery = true)
    List<ISmUserDto> findWorkOnlineInSabun(@Param("sabun") String sabun);

    @Query(value = "select count(a.sabun) from users a inner join sm_user su on a.sabun = su.sabun\n" +
            "and su.work_id = :workId and a.online_yn = true", nativeQuery = true)
    long countByIdWorkId(@Param("workId") String workId);

    @Query(value = "select count(a.sabun) from users a inner join sm_user su on a.sabun = su.sabun\n" +
            "and su.work_id = :workId and a.online_yn = true and a.sabun != :sabun", nativeQuery = true)
    long countByIdWorkIdExceptSabun(@Param("workId") String workId, @Param("sabun") String sabun);
}