package logic

import (
	"context"

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

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

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

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

func (l *SearchChatMessagesLogic) SearchChatMessages(in *pb.SearchChatMessagesReq) (*pb.SearchChatMessagesResp, error) {
	store := l.svcCtx.Store
	store.Mu.RLock()
	defer store.Mu.RUnlock()

	msgIDs := store.SessionMessages[in.GetSessionId()]
	var results []*pb.ChatMessages
	for _, id := range msgIDs {
		msg, ok := store.Messages[id]
		if !ok {
			continue
		}
		if in.SenderId != nil && msg.SenderId != *in.SenderId {
			continue
		}
		results = append(results, msg)
	}

	limit := in.GetLimit()
	if limit <= 0 {
		limit = 20
	}
	offset := in.GetPage() * limit
	if offset >= int64(len(results)) {
		return &pb.SearchChatMessagesResp{}, nil
	}
	end := offset + limit
	if end > int64(len(results)) {
		end = int64(len(results))
	}

	return &pb.SearchChatMessagesResp{ChatMessages: results[offset:end]}, nil
}
