package chatrecords

import (
	"context"
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"strconv"
	"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 GptsGetApiSessionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GptsGetApiSessionLogic) GptsGetApiSession(req *types.GptsSessionReq, tokenStr string) (*types.GptsSessionResp, error) {
	resp := types.GptsSessionResp{}

	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("用户不允许登陆")
	}

	limit := strconv.Itoa(*req.Limit)
	var lastId string
	if req.LastId != nil && *req.LastId != "" {
		lastId = *req.LastId
	}

	employeeItem, err := l.svcCtx.DB.Employee.Query().Where(employee.ID(*req.AgentId)).Only(l.ctx)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("智能体不存在")
	}

	user := fmt.Sprintf("%s-%d", userId, *req.AgentId)
	response, err := dify.GetSessionList(employeeItem.APIBase, employeeItem.APIKey, user, lastId, limit)
	if err != nil {
		return &resp, nil
	}

	resp.Data.HasMore = response.HasMore
	for _, v := range response.Data {
		resp.Data.Data = append(resp.Data.Data, types.Session{
			Id:        &v.ID,
			Name:      &v.Name,
			Inputs:    &v.Inputs,
			CreatedAt: tea.Int(int(v.CreatedAt)),
		})
	}

	return &resp, nil
}
