package client

import (
	"context"

	"google.golang.org/grpc"
	userv1 "hyapp.local/api/proto/user/v1"
	"hyapp/pkg/appcode"
)

// GRPCRegionSource reads active region IDs from user-service region master data.
type GRPCRegionSource struct {
	client userv1.RegionAdminServiceClient
}

// NewGRPCRegionSource creates a region source backed by user-service gRPC.
func NewGRPCRegionSource(conn *grpc.ClientConn) *GRPCRegionSource {
	return &GRPCRegionSource{client: userv1.NewRegionAdminServiceClient(conn)}
}

// ListActiveRegionIDs returns positive active region IDs; GLOBAL region 0 is not an IM region group.
func (s *GRPCRegionSource) ListActiveRegionIDs(ctx context.Context) ([]int64, error) {
	resp, err := s.client.ListRegions(ctx, &userv1.ListRegionsRequest{
		Meta: &userv1.RequestMeta{
			RequestId: "broadcast-region-reconcile",
			Caller:    "activity-service",
			AppCode:   appcode.FromContext(ctx),
		},
		Status: "active",
	})
	if err != nil {
		return nil, err
	}
	regionIDs := make([]int64, 0, len(resp.GetRegions()))
	for _, region := range resp.GetRegions() {
		if region.GetRegionId() > 0 {
			regionIDs = append(regionIDs, region.GetRegionId())
		}
	}
	return regionIDs, nil
}
