package com.kospo.talk.repository;

import com.kospo.talk.model.Talk;
import com.kospo.talk.model.Talk;
import com.kospo.talk.payload.ITalkGroupDto;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.util.List;

public interface TalkRepository extends JpaRepository<Talk, String> {

    Talk findByTalkIdAndInsSabun(String talkId, String insSabun);

    Talk findByReqId(String reqId);

    @Query(value="select t.* from talk t inner join talk_member tm on tm.talk_id = t.talk_id and tm.sabun = :sabun and tm.delete_yn = false and tm.dummy_yn = false", nativeQuery = true)
    List<Talk> findByMemberSabun(@Param("sabun") String sabun);

    @Query(value="select t.talk_id from talk t inner join talk_member tm on tm.talk_id = t.talk_id and tm.sabun = :sabun and tm.delete_yn = false and tm.dummy_yn = false", nativeQuery = true)
    List<String> findTalkIdListBySabun(@Param("sabun") String sabun);

    @Query(value="select t.talk_id from talk t inner join talk_member tm on tm.talk_id = t.talk_id and tm.sabun = :sabun and tm.delete_yn = false and tm.dummy_yn = false and last_message_date > :insDate ::timestamp", nativeQuery = true)
    List<String> findTalkIdListBySabunMore(@Param("sabun") String sabun, @Param("insDate") String insDate);

    long countByWorkIdAndStartYn(String workId, boolean startYn);

    @Query(value = "with b as (select t.*\n" +
            "           from talk t\n" +
            "    inner join talk_member tm\n" +
            "           on t.talk_id = tm.talk_id\n" +
            "           and tm.talk_id not in (\n" +
            "                select talk_id\n" +
            "                  from talk_member tm\n" +
            "                  where tm.sabun = :sabun\n" +
            "                  group by talk_id)\n" +
            "           )\n" +
            "select b.*\n" +
            "from b\n" +
            "         inner join sm_user su on b.work_id = su.work_id\n" +
            "    and su.sabun = :sabun and start_yn = true\n" +
            "group by b.talk_id,\n" +
            "         b.work_id,\n" +
            "         b.ins_name,\n" +
            "         b.ins_sabun,\n" +
            "         b.ins_date,\n" +
            "         b.upd_sabun,\n" +
            "         b.close_yn,\n" +
            "         b.start_yn,\n" +
            "         b.rating_yn,\n" +
            "         b.last_message,\n" +
            "         b.last_message_date,\n" +
            "         b.comp_yn,\n" +
            "         b.req_id\n" +
            "order by b.ins_date desc\n" +
            "limit :end offset :start", nativeQuery = true)
    List<Talk> findTalkGroup(@Param("sabun") String sabun, @Param("start") Integer start, @Param("end") Integer end);

}