package com.sikey.wa04.business.infrastructure.repository;

import com.sikey.wa04.business.infrastructure.dto.model.ContactModel;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.List;

@Repository
public interface ContactRepository extends JpaRepository<ContactModel, Long> {
    List<ContactModel> findByChildId(@Size(max = 36) String childId);

    /**
     * id降序排序查询联系人列表
     * @param childId
     * @return
     */
    List<ContactModel> findByChildIdOrderByIdAsc(@Size(max = 36) String childId);

    void deleteByChildIdAndRefId(@Size(max = 36) String childId, @Size(max = 36) @NotNull String refId);

    ContactModel findByChildIdAndRefId(@Size(max = 36) String childId, @Size(max = 36) @NotNull String refId);

    List<ContactModel> findByRefId(String refId);

    void deleteByChildId(String childId);

    void deleteByRefId(String refId);

    void deleteByRefIdIn(List<String> refIds);

    void deleteByChildIdInAndRefId(List<String> childIds, String refId);

    void deleteByChildIdIn(List<String> childIds);

    @Transactional
    @Modifying
    @Query("update ContactModel m set m.remarkName = :remarkName,m.remarkAvatar = :remarkAvatar,m.updatedAt = :updatedAt where m.childId = :cId and m.refId =:childId")
    void updateContactByChildId(String remarkName, String remarkAvatar, Instant updatedAt, String cId, String childId);

    @Transactional
    @Modifying
    @Query("update ContactModel m set m.refId = :newRefId, m.updatedAt = :updatedAt where m.childId = :cId and m.refId = :refId")
    void updateByRefIdAndChildId(
            @Param("cId") String cId,
            @Param("refId") String refId,
            @Param("newRefId") String newRefId,
            @Param("updatedAt") Instant updatedAt
    );

}
