String buildGlobalKey(String serverId, String ratingKey) => '$serverId:$ratingKey';

/// Separator used by profile-owned rows whose public media identity is still
/// [buildGlobalKey]. Profile ids are generated by the app and do not contain
/// this character.
const String profileScopedGlobalKeySeparator = '|';

/// Builds a profile-owned sync-rule key from [profileId] and public media id.
String buildProfileScopedGlobalKey(String profileId, String serverId, String ratingKey) {
  return '$profileId$profileScopedGlobalKeySeparator${buildGlobalKey(serverId, ratingKey)}';
}

/// Parses a globalKey string (format: "serverId:ratingKey") into its components.
///
/// Returns `null` if the key does not contain a colon separator.
/// Uses [indexOf] so ratingKeys containing colons are handled correctly.
({String serverId, String ratingKey})? parseGlobalKey(String globalKey) {
  final idx = globalKey.indexOf(':');
  if (idx < 0) return null;
  return (serverId: globalKey.substring(0, idx), ratingKey: globalKey.substring(idx + 1));
}

/// Parses a profile-owned sync-rule key, returning `null` for legacy public keys.
({String profileId, String serverId, String ratingKey})? parseProfileScopedGlobalKey(String globalKey) {
  final idx = globalKey.indexOf(profileScopedGlobalKeySeparator);
  if (idx < 0) return null;
  final publicKey = parseGlobalKey(globalKey.substring(idx + 1));
  if (publicKey == null) return null;
  return (profileId: globalKey.substring(0, idx), serverId: publicKey.serverId, ratingKey: publicKey.ratingKey);
}
