package services

import (
	"ai_scheduler/internal/biz"
	errors "ai_scheduler/internal/data/error"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg/validate"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/log"
	"strings"
)

type HistoryService struct {
	chatRepo *biz.ChatHistoryBiz
}

func NewHistoryService(chatRepo *biz.ChatHistoryBiz) *HistoryService {
	return &HistoryService{
		chatRepo: chatRepo,
	}
}

// GetHistoryService 获取会话历史
func (h *HistoryService) List(c *fiber.Ctx) error {
	var query entitys.ChatHistQuery
	if err := c.BodyParser(&query); err != nil {
		return err
	}
	// 校验参数
	if query.SessionID == "" {
		return errors.SessionNotFound
	}
	if query.Page <= 0 {
		query.Page = 1
	}
	if query.PageSize <= 0 {
		query.PageSize = 10
	}

	// 查询历史
	history, err := h.chatRepo.List(c.Context(), &query)
	if err != nil {
		return err
	}

	return c.JSON(history)
}

func (h *HistoryService) UpdateContent(c *fiber.Ctx) error {
	var req entitys.UpdateContentRequest
	if err := c.BodyParser(&req); err != nil {
		return err
	}
	// 校验参数
	msg, err := validate.Struct(req)
	if err != nil {
		log.Error(c.UserContext(), "参数错误 error: ", err)
		return errors.NewBusinessErr(errors.InvalidParamCode, strings.Join(msg, ";"))
	}

	// 更新历史
	return h.chatRepo.UpdateContent(c.Context(), &req)
}
