package chatrecord

import (
	"fmt"
	"mini_server/internal/dao"
	"mini_server/internal/server/help"
	"mini_server/internal/server/httpreply"
	"net/http"

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

type ExistsRequest struct {
	RoleId int32 `form:"role_id" binding:"min=1"` // 角色ID
}

type ExistsReply struct {
	Exists bool `json:"exists"`
}

func Exists(c *gin.Context) {
	reply := httpreply.NewDefaultReplyData()
	defer httpreply.Reply(c, reply)

	//解析请求参数
	var request ExistsRequest
	if err := c.ShouldBind(&request); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid json data, err:%v", err)
		return
	}

	userId, ok := help.GetUserId(c)
	if !ok {
		reply.Status = http.StatusNotFound
		reply.Message = "无法获取用户信息"
		return
	}

	// 在数据库中查询，是否存在角色和用户的聊天记录。
	exists, err := dao.ChatRecord_Exists(userId, request.RoleId)
	if err != nil {
		logrus.Errorf("数据库查询是否存在聊天记录时失败，userId:%d,roleId:%d,err:%v", userId, request.RoleId, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "数据库查询是否存在聊天记录时失败"
		return
	}

	reply.Data = ExistsReply{Exists: exists}
}
