package client

import (
	"context"

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

// GRPCUserTargetSource reads fanout target user IDs from user-service instead of activity owning user data.
type GRPCUserTargetSource struct {
	client userv1.UserServiceClient
}

// NewGRPCUserTargetSource creates a user-service backed target source for message fanout workers.
func NewGRPCUserTargetSource(conn *grpc.ClientConn) *GRPCUserTargetSource {
	return &GRPCUserTargetSource{client: userv1.NewUserServiceClient(conn)}
}

// ListFanoutUserIDs returns a stable user_id cursor page for user-service backed fanout scopes.
func (s *GRPCUserTargetSource) ListFanoutUserIDs(ctx context.Context, query messageservice.TargetQuery) ([]int64, int64, bool, error) {
	resp, err := s.client.ListUserIDs(ctx, &userv1.ListUserIDsRequest{
		Meta: &userv1.RequestMeta{
			RequestId: "message-fanout-worker",
			Caller:    "activity-service",
			AppCode:   appcode.FromContext(ctx),
		},
		TargetScope:  query.TargetScope,
		CursorUserId: query.CursorUserID,
		PageSize:     int32(query.PageSize),
		RegionId:     query.RegionID,
		Country:      query.Country,
	})
	if err != nil {
		return nil, query.CursorUserID, false, err
	}
	return resp.GetUserIds(), resp.GetNextCursorUserId(), resp.GetDone(), nil
}
