package logic

import (
	"context"
	"errors"

	"juwan-backend/app/chat/rpc/internal/svc"
	"juwan-backend/app/chat/rpc/pb"

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

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

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

func (l *AddChatMessagesLogic) AddChatMessages(in *pb.AddChatMessagesReq) (*pb.AddChatMessagesResp, error) {
	if in.GetSessionId() <= 0 {
		return nil, errors.New("sessionId is required")
	}
	if in.GetSenderId() <= 0 {
		return nil, errors.New("senderId is required")
	}
	if in.GetContent() == "" {
		return nil, errors.New("content is required")
	}

	store := l.svcCtx.Store
	store.Mu.Lock()
	defer store.Mu.Unlock()

	if _, ok := store.Sessions[in.GetSessionId()]; !ok {
		return nil, errors.New("session not found")
	}

	now := nowUnix(0)
	msgType := in.GetType()
	if msgType == "" {
		msgType = "text"
	}

	msg := &pb.ChatMessages{
		Id:        store.NextMessage(),
		SessionId: in.GetSessionId(),
		SenderId:  in.GetSenderId(),
		Type:      msgType,
		Content:   in.GetContent(),
		CreatedAt: now,
	}
	store.Messages[msg.Id] = msg
	store.SessionMessages[in.GetSessionId()] = append(store.SessionMessages[in.GetSessionId()], msg.Id)

	session := store.Sessions[in.GetSessionId()]
	session.LastMessage = in.GetContent()
	session.LastMessageAt = now
	session.UpdatedAt = now

	return &pb.AddChatMessagesResp{Id: msg.Id}, nil
}
