package service

import (
	"context"
	"log/slog"

	"hyapp/pkg/logx"
)

// ReleaseLoadedRoomLeases 释放当前节点仍持有的已加载房间 lease。
// 该方法只应在 gRPC 已停止接新请求并完成 in-flight drain 后调用；提前释放会破坏单房间单 owner。
func (s *Service) ReleaseLoadedRoomLeases(ctx context.Context) {
	if s == nil || s.directory == nil {
		return
	}
	for _, roomRef := range s.loadedRoomRefs() {
		released, err := s.directory.ReleaseOwner(ctx, runtimeRoomKey(roomRef.AppCode, roomRef.RoomID), s.nodeID)
		if err != nil {
			logx.Warn(ctx, "room_lease_release_failed",
				slog.String("node_id", s.nodeID),
				slog.String("app_code", roomRef.AppCode),
				slog.String("room_id", roomRef.RoomID),
				slog.String("error", err.Error()),
			)
			continue
		}
		if released {
			logx.Info(ctx, "room_lease_released",
				slog.String("node_id", s.nodeID),
				slog.String("app_code", roomRef.AppCode),
				slog.String("room_id", roomRef.RoomID),
			)
		}
	}
}
