// Code generated by hertz generator.

package core

import (
	"common/kitex_gen/douyin/rpc"
	"common/utils"
	"context"

	core "gateway/biz/model/douyin/core"
	"gateway/internal/db"
	"gateway/internal/jwt"
	"gateway/internal/services"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

// Chat .
// @router /douyin/message/chat/ [GET]
func Chat(ctx context.Context, c *app.RequestContext) {
	var err error
	var req core.DouyinMessageChatRequest
	err = c.BindAndValidate(&req)
	if err != nil {
		utils.InvalidInput(c, err)
		return
	}

	user, err := jwt.AuthorizedUser(c, &req.Token)
	if err != nil || user == 0 {
		utils.ErrorUnauthorized.Write(c)
		return
	}

	if !db.UserExists(req.ToUserId) {
		utils.ErrorNoSuchUser.Write(c)
		return
	}

	r, err := services.Message.Chat(ctx, &rpc.DouyinMessageChatRequest{
		RequestUserId: user,
		ToUserId:      req.ToUserId,
		PreMsgTime:    req.PreMsgTime,
	})
	if err != nil {
		utils.ErrorRpcTimeout.Write(c)
		return
	}
	if utils.RpcError(c, r.StatusCode) {
		return
	}

	resp := new(core.DouyinMessageChatResponse)
	resp.MessageList = make([]*core.Message, 0, len(r.MessageList))
	for _, msg := range r.MessageList {
		resp.MessageList = append(resp.MessageList, &core.Message{
			Id:         msg.Id,
			FromUserId: msg.FromUserId,
			ToUserId:   msg.ToUserId,
			Content:    msg.Content,
			CreateTime: msg.CreateTime,
		})
	}

	c.JSON(consts.StatusOK, resp)
}

// Message .
// @router /douyin/message/action/ [POST]
func Message(ctx context.Context, c *app.RequestContext) {
	var err error
	var req core.DouyinMessageActionRequest
	err = c.BindAndValidate(&req)
	if err != nil {
		utils.InvalidInput(c, err)
		return
	}

	user, err := jwt.AuthorizedUser(c, &req.Token)
	if err != nil || user == 0 {
		utils.ErrorUnauthorized.Write(c)
		return
	}

	if !db.UserExists(req.ToUserId) {
		utils.ErrorNoSuchUser.Write(c)
		return
	}

	r, err := services.Message.Message(ctx, &rpc.DouyinMessageActionRequest{
		RequestUserId: user,
		ToUserId:      req.ToUserId,
		ActionType:    req.ActionType,
		Content:       req.Content,
	})
	if err != nil {
		utils.ErrorRpcTimeout.Write(c)
		return
	}
	if utils.RpcError(c, r.StatusCode) {
		return
	}

	resp := new(core.DouyinMessageActionResponse)

	c.JSON(consts.StatusOK, resp)
}
