package eu.friedcutlet.yokan.database import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json /** * Snapshot storage used by the browser backend and as the one-shot legacy * loader for Room migration. Non-web runtime persistence is owned by Room; * the browser uses `save()` for its deferred snapshot persistence. */ interface DatabaseSnapshotStore { fun load(): YokanDatabaseSnapshot? fun save(snapshot: YokanDatabaseSnapshot) } expect fun createDefaultDatabaseSnapshotStore(): DatabaseSnapshotStore /** * Pick the persistence backend. Android/desktop/iOS use Room (per-row * INSERTs, fast); the browser keeps the whole-snapshot JSON store because * neither Room nor bundled SQLite ship wasm artifacts. */ expect fun createDefaultDatabase(): YokanDatabase /** Low-level storage factory; only a registry/session coordinator may publish an additional profile. */ expect fun createProfileDatabase(profileId: eu.friedcutlet.yokan.domain.ProfileId): YokanDatabase @Serializable data class PersistedDatabaseSnapshot( val schemaVersion: Int = CurrentDatabaseSchemaVersion, val snapshot: YokanDatabaseSnapshot, ) const val CurrentDatabaseSchemaVersion = 1 val DatabaseJson = Json { encodeDefaults = true ignoreUnknownKeys = true prettyPrint = true } fun encodeDatabaseSnapshot(snapshot: YokanDatabaseSnapshot): String = DatabaseJson.encodeToString(PersistedDatabaseSnapshot(snapshot = snapshot)) fun decodeDatabaseSnapshot(raw: String): YokanDatabaseSnapshot? = runCatching { normalizeLegacySnapshot(raw, DatabaseJson.decodeFromString(raw).snapshot) }.recoverCatching { normalizeLegacySnapshot(raw, DatabaseJson.decodeFromString(raw)) }.getOrNull() private fun normalizeLegacySnapshot(raw: String, snapshot: YokanDatabaseSnapshot): YokanDatabaseSnapshot { if (raw.contains("\"hubRecoveryPending\"") && raw.contains("\"hubBootstrapComplete\"")) { return snapshot } return snapshot.copy( syncPreferences = snapshot.syncPreferences.map { preference -> if (preference.hubEpoch > 0 || preference.hubHead > 0 || preference.hubRecoveryPending || (!preference.server.isNullOrBlank() && !preference.authToken.isNullOrBlank()) ) { preference.copy(hubBootstrapComplete = true) } else { preference } }, ) }