package client

import (
	"context"
	"strings"
	"time"

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

// GRPCRoomBroadcastSource 通过 room-service 的 owner 读模型补齐 game_win 跳转所需展示状态。
// activity-service 不缓存密码或房间状态，只把本次结算时读取到的 locked 快照固化进 IM payload。
type GRPCRoomBroadcastSource struct {
	client roomv1.RoomQueryServiceClient
}

func NewGRPCRoomBroadcastSource(conn *grpc.ClientConn) *GRPCRoomBroadcastSource {
	return &GRPCRoomBroadcastSource{client: roomv1.NewRoomQueryServiceClient(conn)}
}

func (s *GRPCRoomBroadcastSource) GetRoomBroadcastSnapshot(ctx context.Context, roomID string) (broadcastservice.RoomBroadcastSnapshot, error) {
	roomID = strings.TrimSpace(roomID)
	resp, err := s.client.AdminGetRoom(ctx, &roomv1.AdminGetRoomRequest{
		Meta: &roomv1.RequestMeta{
			RequestId: "activity-game-win-room:" + roomID,
			AppCode:   appcode.FromContext(ctx),
			SentAtMs:  time.Now().UTC().UnixMilli(),
		},
		RoomId: roomID,
	})
	if err != nil {
		return broadcastservice.RoomBroadcastSnapshot{}, err
	}
	room := resp.GetRoom()
	if room == nil {
		return broadcastservice.RoomBroadcastSnapshot{RoomID: roomID}, nil
	}
	return broadcastservice.RoomBroadcastSnapshot{
		RoomID:          room.GetRoomId(),
		Title:           room.GetTitle(),
		Locked:          room.GetLocked(),
		OwnerUserID:     room.GetOwnerUserId(),
		VisibleRegionID: room.GetVisibleRegionId(),
		Status:          room.GetStatus(),
	}, nil
}
