package com.agent.management.repository;

import com.agent.management.model.entity.ChatSession;
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 java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * Agent 对话会话 Repository。
 *
 * <p>对应设计文档 §4.3.1。</p>
 */
@Repository
public interface ChatSessionRepository extends JpaRepository<ChatSession, Long> {

    Optional<ChatSession> findBySessionUuid(String sessionUuid);

    /** 列表分页：按状态过滤，按 last_message_at 倒序 */
    List<ChatSession> findByStatusOrderByLastMessageAtDesc(String status);

    /** 列表：置顶优先，其次按 last_message_at 倒序 */
    @Query("SELECT s FROM ChatSession s WHERE s.status = :status ORDER BY s.pinned DESC, s.lastMessageAt DESC")
    List<ChatSession> findActiveOrderByPinnedAndLastMessageAtDesc(@Param("status") String status);

    /** 触发 last_message_at 更新；同时同步 updatedAt */
    @Modifying
    @Query("UPDATE ChatSession s SET s.lastMessageAt = :ts, s.updatedAt = :ts WHERE s.id = :id")
    int touch(@Param("id") Long id, @Param("ts") LocalDateTime ts);

    /** 自动标题：仅当 title 为 null 时设置 */
    @Modifying
    @Query("UPDATE ChatSession s SET s.title = :title WHERE s.id = :id AND s.title IS NULL")
    int setTitleIfNull(@Param("id") Long id, @Param("title") String title);
}
