package host

import (
	"context"
	"strings"
	"time"

	"hyapp/pkg/xerr"
	hostdomain "hyapp/services/user-service/internal/domain/host"
)

const maxHostStatsRange = 366 * 24 * time.Hour

// GetHostEngagementStats 读取 user-service 拥有的统计事实；收益和送礼人数由 wallet-service 聚合。
func (s *Service) GetHostEngagementStats(ctx context.Context, query hostdomain.EngagementStatsQuery) (hostdomain.EngagementStats, error) {
	if s.repository == nil {
		return hostdomain.EngagementStats{}, xerr.New(xerr.Unavailable, "host repository is not configured")
	}
	if query.HostUserID <= 0 || query.StartAtMS <= 0 || query.EndAtMS <= query.StartAtMS {
		return hostdomain.EngagementStats{}, xerr.New(xerr.InvalidArgument, "host stats range is invalid")
	}
	if query.EndAtMS-query.StartAtMS > int64(maxHostStatsRange/time.Millisecond) {
		return hostdomain.EngagementStats{}, xerr.New(xerr.InvalidArgument, "host stats range is too large")
	}
	return s.repository.GetHostEngagementStats(ctx, query)
}

// RecordPrivateMessageEvent 只保存发送者、接收者和事件时间；消息正文不进入统计库。
func (s *Service) RecordPrivateMessageEvent(ctx context.Context, event hostdomain.PrivateMessageEvent) (bool, error) {
	if s.repository == nil {
		return false, xerr.New(xerr.Unavailable, "host repository is not configured")
	}
	event.EventID = strings.TrimSpace(event.EventID)
	if event.EventID == "" || len(event.EventID) > 128 || event.SenderUserID <= 0 || event.TargetUserID <= 0 || event.OccurredAtMS <= 0 {
		return false, xerr.New(xerr.InvalidArgument, "private message event is invalid")
	}
	return s.repository.RecordPrivateMessageEvent(ctx, event)
}
