package server

import (
	"net/http"
	"strings"

	"agent/internal/agent"

	"github.com/gin-gonic/gin"
)

// listSessions 会话列表，支持 ?q=<关键词> 搜索、?limit=&offset= 分页。
func (s *Server) listSessions(c *gin.Context) {
	query := strings.TrimSpace(c.Query("q"))
	var sessions []agent.SessionSummary
	if query != "" {
		sessions = s.store.Search(query)
	} else {
		sessions = s.store.List()
	}
	limit, offset := parsePagination(c)
	if offset > 0 || limit > 0 {
		start := offset
		if start > len(sessions) {
			start = len(sessions)
		}
		end := len(sessions)
		if limit > 0 && start+limit < end {
			end = start + limit
		}
		sessions = sessions[start:end]
	}
	ok(c, gin.H{"sessions": sessions})
}

func (s *Server) createSession(c *gin.Context) {
	session := s.store.Create()
	c.JSON(http.StatusCreated, session)
}

func (s *Server) getSession(c *gin.Context) {
	session, found := s.store.Get(c.Param("id"))
	if !found {
		fail(c, http.StatusNotFound, "会话不存在")
		return
	}
	ok(c, gin.H{"session": session})
}

// sessionMessages 分页返回会话消息（offset 从最新一条往前数），
// 响应含 has_more 与 total 供前端"加载更早"。
func (s *Server) sessionMessages(c *gin.Context) {
	id := c.Param("id")
	total, exists := s.store.TotalMessages(id)
	if !exists {
		fail(c, http.StatusNotFound, "会话不存在")
		return
	}
	limit, offset := parsePagination(c)
	if limit <= 0 || limit > 200 {
		limit = 50
	}
	messages, _, hasMore := s.store.Messages(id, limit, offset)
	ok(c, gin.H{
		"messages": messages,
		"has_more": hasMore,
		"total":    total,
	})
}

func (s *Server) deleteSession(c *gin.Context) {
	id := c.Param("id")
	if !s.store.Delete(id) {
		fail(c, http.StatusNotFound, "会话不存在")
		return
	}
	// 释放会话持有的运行时资源（会话锁与 live 注册），避免内存泄漏
	s.agent.ForgetSession(id)
	c.Status(http.StatusNoContent)
}

// clearSession 清空会话历史消息（保留会话）。
func (s *Server) clearSession(c *gin.Context) {
	if !s.store.Clear(c.Param("id")) {
		fail(c, http.StatusNotFound, "会话不存在")
		return
	}
	c.Status(http.StatusNoContent)
}
