package service

import (
	"context"
	"strings"

	roomv1 "hyapp.local/api/proto/room/v1"
	"hyapp/pkg/roomid"
	"hyapp/pkg/xerr"
)

// ResolveRoomAppCode 让已验签的腾讯 RTC 回调从房间事实解析租户。
// room-service 是房间归属 owner；gateway 不应信任 URL 中可伪造、也容易写死的 app_code。
func (s *Service) ResolveRoomAppCode(ctx context.Context, req *roomv1.ResolveRoomAppCodeRequest) (*roomv1.ResolveRoomAppCodeResponse, error) {
	roomID := strings.TrimSpace(req.GetRoomId())
	if !roomid.ValidStringID(roomID) {
		return nil, xerr.New(xerr.InvalidArgument, "room_id is invalid")
	}
	meta, exists, err := s.repository.GetRoomMetaByGlobalID(ctx, roomID)
	if err != nil {
		return nil, err
	}
	if !exists || strings.TrimSpace(meta.AppCode) == "" {
		return nil, xerr.New(xerr.NotFound, "room not found")
	}
	return &roomv1.ResolveRoomAppCodeResponse{AppCode: meta.AppCode}, nil
}
