package com.diegocayo.organizame.data.local.preferences

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.first
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class PreferencesDataStore @Inject constructor(
    @ApplicationContext private val context: Context,
    private val dataStore: DataStore<Preferences>
) {
    suspend fun clearPreferences() {
        try {
            val currentPrefs = dataStore.data.first()

            currentPrefs.asMap().keys.forEach { key ->
                dataStore.edit { preferences ->
                    preferences.remove(key)
                }
            }

            dataStore.edit { preferences ->
                preferences.clear()
            }

            val emptyPrefs = dataStore.data.first()
            if (emptyPrefs != emptyPreferences()) {
                dataStore.edit { preferences ->
                    preferences.clear()
                }
            }
        } catch (e: Exception) {
            dataStore.edit { preferences ->
                preferences.clear()
            }
        }
    }
} 