package client

import (
	"context"

	"google.golang.org/grpc"
	userv1 "hyapp.local/api/proto/user/v1"
	"hyapp/pkg/appcode"
	domain "hyapp/services/activity-service/internal/domain/cpweeklyrank"
)

// GRPCCPWeeklyRankSource reads CP weekly rank snapshots from user-service, the owner of CP relationship facts.
type GRPCCPWeeklyRankSource struct {
	client userv1.UserCPInternalServiceClient
}

func NewGRPCCPWeeklyRankSource(conn *grpc.ClientConn) *GRPCCPWeeklyRankSource {
	return &GRPCCPWeeklyRankSource{client: userv1.NewUserCPInternalServiceClient(conn)}
}

func (s *GRPCCPWeeklyRankSource) ListCPWeeklyRankEntries(ctx context.Context, relationType string, startMS int64, endMS int64, limit int32) ([]domain.Entry, error) {
	resp, err := s.client.ListCPWeeklyRankEntries(ctx, &userv1.ListCPWeeklyRankEntriesRequest{
		Meta: &userv1.RequestMeta{
			RequestId: "cp-weekly-rank",
			Caller:    "activity-service",
			AppCode:   appcode.FromContext(ctx),
		},
		RelationType: relationType,
		StartMs:      startMS,
		EndMs:        endMS,
		Limit:        limit,
	})
	if err != nil {
		return nil, err
	}
	entries := make([]domain.Entry, 0, len(resp.GetEntries()))
	for _, item := range resp.GetEntries() {
		entries = append(entries, domain.Entry{
			Rank:            item.GetRank(),
			RelationshipID:  item.GetRelationshipId(),
			RelationType:    item.GetRelationType(),
			Score:           item.GetScore(),
			UserA:           cpWeeklyRankUserFromProto(item.GetUserA()),
			UserB:           cpWeeklyRankUserFromProto(item.GetUserB()),
			FormedAtMS:      item.GetFormedAtMs(),
			UpdatedAtMS:     item.GetUpdatedAtMs(),
			FirstScoredAtMS: item.GetFirstScoredAtMs(),
			LastScoredAtMS:  item.GetLastScoredAtMs(),
		})
	}
	return entries, nil
}

func cpWeeklyRankUserFromProto(user *userv1.CPIntimacyLeaderboardUser) domain.User {
	if user == nil {
		return domain.User{}
	}
	return domain.User{
		UserID:        user.GetUserId(),
		DisplayUserID: user.GetDisplayUserId(),
		Username:      user.GetUsername(),
		Avatar:        user.GetAvatar(),
	}
}
