package richtext

import (
	"context"
	"fmt"
	"strings"
)

// resolveCollabRoomID returns a stable Hocuspocus room for a document on the owner's drive.
// Auth sessions, public share links, and guests all join the same room when editing the same sidecar.
func (s *Service) resolveCollabRoomID(ctx context.Context, ownerID, ownerSidecarPath string) (string, error) {
	ownerID = strings.TrimSpace(ownerID)
	ownerSidecarPath = normalizePath(ownerSidecarPath)
	if ownerID == "" || ownerSidecarPath == "" {
		return "", fmt.Errorf("collab room: missing owner or path")
	}
	if rev, err := s.nc.FileRevision(ctx, ownerID, ownerSidecarPath); err == nil && rev.FileID > 0 {
		return fmt.Sprintf("rt:%s:%d", ownerID, rev.FileID), nil
	}
	return fmt.Sprintf("rt:%s:%s", ownerID, hashPath(ownerSidecarPath)), nil
}

func (s *Service) ownerSidecarPathForPublic(ctx context.Context, token, password, clientCanonical, displayName string) (ownerID, ownerPath string, err error) {
	binding, err := s.nc.ResolvePublicShareBinding(ctx, token, password)
	if err != nil {
		return "", "", err
	}
	return binding.OwnerID, binding.OwnerPathForClient(clientCanonical, displayName), nil
}
