can you review my error handling and detect any unused, redundant or code smells bugs or performance issues in this or detect any  OVER-ENGINEERED CODE // Error types
sealed interface WidgetError {
    data object NotFound : WidgetError
    data object InvalidWidget : WidgetError
    data class Storage(val message: String) : WidgetError
    data class UpdateFailed(val message: String) : WidgetError
}

// Outcome sealed class
sealed class Outcome<out T> {
    data class Ok<T>(val value: T) : Outcome<T>()
    data class Err(val error: WidgetError) : Outcome<Nothing>()

    inline fun <R> map(transform: (T) -> R): Outcome<R> = when (this) {
        is Ok -> Ok(transform(value))
        is Err -> this
    }

    inline fun <R> flatMap(transform: (T) -> Outcome<R>): Outcome<R> = when (this) {
        is Ok -> transform(value)
        is Err -> this
    }

    fun getOrNull(): T? = when (this) {
        is Ok -> value
        is Err -> null
    }
}

// Helper function for widget operations
inline fun <T> widgetOperation(block: () -> T): Outcome<T> = try {
    Outcome.Ok(block())
} catch (e: Exception) {
    Outcome.Err(
        when {
            e.message?.contains("not found") == true -> WidgetError.NotFound
            e.message?.contains("invalid") == true -> WidgetError.InvalidWidget
            e is IOException -> WidgetError.Storage(e.message ?: "Storage error")
            else -> WidgetError.UpdateFailed(e.message ?: "Update failed")
        }
    )
}


fun getErrorMessage(error: WidgetError): String = when (error) {
    is WidgetError.NotFound -> "Widget not found"
    is WidgetError.InvalidWidget -> "Invalid widget"
    is WidgetError.Storage -> "Save failed"
    is WidgetError.UpdateFailed -> "Update failed"
}

// Extension functions for easier usage
fun <T> Outcome<T>.onSuccess(action: (T) -> Unit): Outcome<T> {
    if (this is Outcome.Ok) action(value)
    return this
}

fun <T> Outcome<T>.onError(action: (WidgetError) -> Unit): Outcome<T> {
    if (this is Outcome.Err) action(error)
    return this
}

fun <T> Outcome<T>.getOrElse(default: () -> T): T = when (this) {
    is Outcome.Ok -> value
    is Outcome.Err -> default()
}
 and     override suspend fun doWork(): Result {
        return when (val outcome = widgetPreferencesManager.updateAllWidgets { cityId ->
            getWeatherDBbyCityIdUseCase(cityId)
        }) {
            is Outcome.Ok -> Result.success()
            is Outcome.Err -> {
                // Log the error for debugging
                Log.e(
                    "WidgetUpdateWorker",
                    "Failed to update widgets: ${getErrorMessage(outcome.error)}"
                )

                // Retry based on error type
                when (outcome.error) {
                    is WidgetError.Storage,
                    is WidgetError.UpdateFailed -> Result.retry()

                    is WidgetError.NotFound,
                    is WidgetError.InvalidWidget -> Result.failure()
                }
            }
        }
    } and class WidgetReceiver : GlanceAppWidgetReceiver(), KoinComponent {

    override val glanceAppWidget: GlanceAppWidget = WeatherWidget()
    private val widgetPreferencesManager: WidgetPreferencesManager by inject()

    private val coroutineScope = CoroutineScope(
        SupervisorJob() + Dispatchers.IO + CoroutineExceptionHandler { _, throwable ->
            // Log error but don't crash
            Log.e("WidgetReceiver", "Coroutine error", throwable)
        }
    )


    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)

        // Trigger immediate update for all widgets
        coroutineScope.launch {
            appWidgetIds.forEach { widgetId ->
                when (val result = widgetPreferencesManager.getWidgetState(widgetId)) {
                    is Outcome.Ok -> {
                        result.value?.let { state ->
                            if (state.weather == null && state.config.selectedCityId != 0L) {
                                // Widget needs weather data
                                WidgetUpdateWorker.schedule(context)
                            }
                        }
                    }

                    is Outcome.Err -> {
                        // Log error but continue with other widgets
                        Log.w("WidgetReceiver", "Failed to get state for widget $widgetId")
                    }
                }
            }
        }
    }


    override fun onDeleted(context: Context, appWidgetIds: IntArray) {
        super.onDeleted(context, appWidgetIds)

        // Clean up widget data
        coroutineScope.launch {
            appWidgetIds.forEach { widgetId ->
                when (widgetPreferencesManager.removeWidget(widgetId)) {
                    is Outcome.Ok -> {
                        // Successfully removed
                    }

                    is Outcome.Err -> {
                        Log.w("WidgetReceiver", "Failed to remove widget $widgetId")
                    }
                }
            }

            // Cancel worker if no widgets remain
            when (val result = widgetPreferencesManager.getAllWidgetIds()) {
                is Outcome.Ok -> {
                    if (result.value.isEmpty()) {
                        WidgetUpdateWorker.cancelScheduled(context)
                    }
                }

                is Outcome.Err -> {
                    Log.w("WidgetReceiver", "Failed to get widget IDs")
                }
            }
        }
    } and // viewmodel    private suspend fun loadWidgetConfig(widgetId: Int) {
        when (val result = widgetPreferencesManager.getWidgetConfig(widgetId)) {
            is Outcome.Ok -> {
                val config = result.value ?: WidgetConfig(widgetId = widgetId)
                updateState { state ->
                    state.copy(
                        config = config,
                        selectedCity = state.citiesById[config.selectedCityId]
                    )
                }
            }

            is Outcome.Err -> {
                updateState { state ->
                    state.copy(
                        error = getErrorMessage(result.error),
                        config = WidgetConfig(widgetId = widgetId)
                    )
                }
            }
        }
    }

    private suspend fun observeWidgetChanges(widgetId: Int) {
        widgetPreferencesManager.observeWidgetState(widgetId)
            .filterNotNull()
            .collect { widgetState ->
                updateState { state ->
                    state.copy(
                        config = widgetState.config,
                        selectedCity = state.citiesById[widgetState.config.selectedCityId]
                    )
                }
            }
    }     fun saveConfiguration() {
        val currentState = _uiState.value

        // Validation
        if (currentState.selectedCity == null) {
            updateState { it.copy(error = "Please select a city before saving") }
            return
        }

        if (currentState.isSaving) return

        viewModelScope.launch {
            updateState { it.copy(isSaving = true, error = null) }

            // Chain operations - stop on first failure
            val saveResult = saveConfigAndWeather(
                currentState.config,
                currentState.selectedCity
            )

            updateState { state ->
                state.copy(
                    isSaving = false,
                    error = when (saveResult) {
                        is Outcome.Ok -> null
                        is Outcome.Err -> getErrorMessage(saveResult.error)
                    }
                )
            }
        }
    }


    private suspend fun saveConfigAndWeather(
        config: WidgetConfig,
        city: Weather
    ): Outcome<Unit> {
        // Save config
        val configResult = widgetPreferencesManager.saveWidgetConfig(currentWidgetId, config)
        if (configResult is Outcome.Err) return configResult

        // Update weather
        val widgetModel = city.mapToWidgetModel()
        return widgetPreferencesManager.updateWidgetWeather(currentWidgetId, widgetModel)
    }