package grpc

import (
	"context"

	userv1 "hyapp.local/api/proto/user/v1"
	"hyapp/pkg/xerr"
	hostdomain "hyapp/services/user-service/internal/domain/host"
)

// GetHostEngagementStats 返回 user-service 拥有的主播互动统计；调用方不能提交聚合值。
func (s *Server) GetHostEngagementStats(ctx context.Context, req *userv1.GetHostEngagementStatsRequest) (*userv1.GetHostEngagementStatsResponse, error) {
	if s.hostSvc == nil {
		return nil, xerr.ToGRPCError(xerr.New(xerr.Unavailable, "host service is not configured"))
	}
	ctx = contextWithApp(ctx, req.GetMeta())
	stats, err := s.hostSvc.GetHostEngagementStats(ctx, hostdomain.EngagementStatsQuery{
		HostUserID: req.GetHostUserId(),
		StartAtMS:  req.GetStartAtMs(),
		EndAtMS:    req.GetEndAtMs(),
	})
	if err != nil {
		return nil, xerr.ToGRPCError(err)
	}
	return &userv1.GetHostEngagementStatsResponse{Stats: &userv1.HostEngagementStats{
		OnlineDurationMs:      stats.OnlineDurationMS,
		ValidMicDurationMs:    stats.ValidMicDurationMS,
		ValidMicDays:          stats.ValidMicDays,
		PrivateMessageSenders: stats.PrivateMessageSenders,
		NewFollowers:          stats.NewFollowers,
	}}, nil
}

// RecordPrivateMessageEvent 只接受 gateway 已鉴权回调产生的最小事件事实。
func (s *Server) RecordPrivateMessageEvent(ctx context.Context, req *userv1.RecordPrivateMessageEventRequest) (*userv1.RecordPrivateMessageEventResponse, error) {
	if s.hostSvc == nil {
		return nil, xerr.ToGRPCError(xerr.New(xerr.Unavailable, "host service is not configured"))
	}
	ctx = contextWithApp(ctx, req.GetMeta())
	created, err := s.hostSvc.RecordPrivateMessageEvent(ctx, hostdomain.PrivateMessageEvent{
		EventID:      req.GetEventId(),
		SenderUserID: req.GetSenderUserId(),
		TargetUserID: req.GetTargetUserId(),
		OccurredAtMS: req.GetOccurredAtMs(),
	})
	if err != nil {
		return nil, xerr.ToGRPCError(err)
	}
	return &userv1.RecordPrivateMessageEventResponse{Created: created}, nil
}
