package client

import (
	"context"

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

// GRPCUserProfileSource 从 user-service 读取活动播报所需的发送者展示资料。
// activity-service 只消费当前快照组装 IM，不复制或拥有用户资料。
type GRPCUserProfileSource struct {
	client userv1.UserServiceClient
}

func NewGRPCUserProfileSource(conn *grpc.ClientConn) *GRPCUserProfileSource {
	return &GRPCUserProfileSource{client: userv1.NewUserServiceClient(conn)}
}

func (s *GRPCUserProfileSource) GetSenderProfile(ctx context.Context, userID int64) (broadcastservice.SenderProfile, error) {
	resp, err := s.client.GetUser(ctx, &userv1.GetUserRequest{
		Meta: &userv1.RequestMeta{
			RequestId: "activity-broadcast-profile",
			Caller:    "activity-service",
			AppCode:   appcode.FromContext(ctx),
		},
		UserId: userID,
	})
	if err != nil {
		return broadcastservice.SenderProfile{}, err
	}
	user := resp.GetUser()
	if user == nil {
		return broadcastservice.SenderProfile{UserID: userID}, nil
	}
	return broadcastservice.SenderProfile{
		UserID:              user.GetUserId(),
		Account:             user.GetDisplayUserId(),
		PrettyDisplayUserID: user.GetPrettyDisplayUserId(),
		Nickname:            user.GetUsername(),
		Avatar:              user.GetAvatar(),
		AvatarFrameURL:      "",
		RegionCode:          user.GetRegionCode(),
	}, nil
}
