package services

import (
	"ai_scheduler/internal/biz"
	errorcode "ai_scheduler/internal/data/error"
	"ai_scheduler/internal/entitys"
	"net/http"

	"github.com/gofiber/fiber/v2"
)

type SessionService struct {
	sessionBiz *biz.SessionBiz
	chatBiz    *biz.ChatHistoryBiz
}

func NewSessionService(sessionBiz *biz.SessionBiz, chatBiz *biz.ChatHistoryBiz) *SessionService {
	return &SessionService{
		sessionBiz: sessionBiz,
		chatBiz:    chatBiz,
	}
}

// SessionInit 初始化会话
func (s *SessionService) SessionInit(c *fiber.Ctx) error {
	req := &entitys.SessionInitRequest{}
	if err := c.BodyParser(req); err != nil {
		return err
	}

	result, err := s.sessionBiz.SessionInit(c.Context(), req)

	if err != nil {
		return err
	}

	return c.JSON(result)
}

// NewSession 新会话
func (s *SessionService) NewSession(c *fiber.Ctx) error {
	req := &entitys.SessionInitRequest{}
	if err := c.BodyParser(req); err != nil {
		return err
	}

	sysConfig, err := s.sessionBiz.GetSysConfig(req.SysId)

	if err != nil {
		return err
	}
	session, err := s.sessionBiz.CreateNew(sysConfig.SysID, req)

	return c.JSON(session)
}

// SessionList 获取会话列表
func (s *SessionService) SessionList(c *fiber.Ctx) error {
	req := &entitys.SessionListRequest{}
	if err := c.BodyParser(req); err != nil {
		return err
	}

	sessionList, err := s.sessionBiz.SessionList(c.Context(), req)

	if err != nil {
		return err
	}

	return c.JSON(fiber.Map{
		"session_list": sessionList,
	})
}

// DeleteSession 删除会话
func (s *SessionService) DeleteSession(c *fiber.Ctx) error {
	req := &entitys.SessionDeleteRequest{}
	if err := c.BodyParser(req); err != nil {
		return err
	}

	err := s.sessionBiz.DeleteSession(c.Context(), req)

	if err != nil {
		return err
	}

	return c.JSON(fiber.Map{
		"message": "success",
	})
}

// RenameSession 会话重命名
func (s *SessionService) RenameSession(c *fiber.Ctx) error {
	req := &entitys.SessionRenameRequest{}
	if err := c.BodyParser(req); err != nil {
		return err
	}
	if req.SessionId == "" || req.NewName == "" {
		return errorcode.NewBusinessErr(http.StatusBadRequest, "新会话名称不能为空")
	}

	err := s.sessionBiz.RenameSession(c.Context(), req)

	if err != nil {
		return err
	}

	return c.JSON(fiber.Map{
		"message": "success",
	})
}
