package chatrecords

import (
	"context"
	"fmt"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent/employee"
	"wechat-api/hook/dify"
	"wechat-api/internal/utils"
	jwtutils "wechat-api/internal/utils/jwt"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GptsRenameApiSessionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGptsRenameApiSessionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GptsRenameApiSessionLogic {
	return &GptsRenameApiSessionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GptsRenameApiSessionLogic) GptsRenameApiSession(req *types.GptsRenameSessionReq, tokenStr string) (*types.BaseMsgResp, error) {
	claims, err := jwtutils.ParseJwtToken(l.svcCtx.Config.Auth.AccessSecret, tokenStr)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("用户未登录")
	}
	userId, ok := claims["userId"].(string)

	if !ok || userId == "" {
		return nil, errorx.NewInvalidArgumentError("用户需要登录")
	}

	userInfo, _ := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: userId})
	valid := utils.CheckGptLogin(userInfo.RoleIds)
	if !valid {
		return nil, errorx.NewInvalidArgumentError("用户不允许登陆")
	}

	resp := types.BaseMsgResp{}
	var conversationId, name string
	var agentId uint64
	if req.ConversationId != nil && *req.ConversationId != "" {
		conversationId = *req.ConversationId
	}
	if req.Name != nil && *req.Name != "" {
		name = *req.Name
	}
	if conversationId == "" {
		return nil, errorx.NewInvalidArgumentError("conversationId is empty")
	}
	if req.AgentId != nil && *req.AgentId > 0 {
		agentId = *req.AgentId
	}
	employeeItem, err := l.svcCtx.DB.Employee.Query().Where(employee.ID(agentId)).Only(l.ctx)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("智能体不存在")
	}

	user := fmt.Sprintf("%s-%d", userId, agentId)
	_, err = dify.RenameSession(employeeItem.APIBase, employeeItem.APIKey, user, name, conversationId)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError(err.Error())
	}

	resp.Msg = "操作成功"
	return &resp, nil
}
