package eu.friedcutlet.yokan.app.profiles import kotlinx.coroutines.CancellationException import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult internal interface ProfileWorkSessions { suspend fun run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult } /** * Checks fresh metadata before opening any database. No lookup uses lastActive or falls back from * an explicit invalid/unavailable owner. Production uses the coordinator's storage lease; retired owners never recreate their data. */ internal class ProfileBackgroundWork( private val registry: ProfileRegistry, private val supported: (ProfileId) -> Boolean, private val sessions: ProfileWorkSessions, ) { suspend fun run( serializedOwner: String?, allowLegacyDefault: Boolean = false, action: suspend (ProfileSession) -> T, ): ProfileWorkResult { currentCoroutineContext().ensureActive() val id = if (serializedOwner == null) { if (!allowLegacyDefault) return ProfileWorkResult.Skipped ProfileId.Default } else { try { ProfileId(serializedOwner) } catch (_: IllegalArgumentException) { return ProfileWorkResult.Skipped } } val snapshot = try { registry.refresh() } catch (error: CancellationException) { throw error } catch (_: Exception) { return ProfileWorkResult.Retry } currentCoroutineContext().ensureActive() if (snapshot.available(id) == null || !supported(id)) return ProfileWorkResult.Skipped return sessions.run(id, action) } }