package id.iiyh.inatrading.core.data.local

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.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "ina_session")

@Singleton
class SessionManager @Inject constructor(
    @ApplicationContext private val context: Context,
) {
    companion object {
        private val TOKEN_KEY    = stringPreferencesKey("auth_token")
        private val EMAIL_KEY    = stringPreferencesKey("user_email")
        private val NAME_KEY     = stringPreferencesKey("user_name")
        private val AVATAR_URL_KEY = stringPreferencesKey("user_avatar_url")
        private val USER_TYPE_KEY = stringPreferencesKey("user_type")
    }

    val token:    Flow<String?> = context.dataStore.data.map { it[TOKEN_KEY] }
    val email:    Flow<String?> = context.dataStore.data.map { it[EMAIL_KEY] }
    val name:     Flow<String?> = context.dataStore.data.map { it[NAME_KEY] }
    val avatarUrl: Flow<String?> = context.dataStore.data.map { it[AVATAR_URL_KEY] }
    val userType: Flow<String?> = context.dataStore.data.map { it[USER_TYPE_KEY] }

    suspend fun saveSession(
        token: String,
        email: String,
        name: String,
        userType: String,
        avatarUrl: String = "",
    ) {
        context.dataStore.edit { prefs ->
            prefs[TOKEN_KEY]     = token
            prefs[EMAIL_KEY]     = email
            prefs[NAME_KEY]      = name
            prefs[AVATAR_URL_KEY] = avatarUrl
            prefs[USER_TYPE_KEY] = userType
        }
    }

    suspend fun saveToken(token: String) {
        context.dataStore.edit { it[TOKEN_KEY] = token }
    }

    suspend fun updateProfile(name: String, email: String, avatarUrl: String? = null) {
        context.dataStore.edit { prefs ->
            prefs[NAME_KEY] = name
            prefs[EMAIL_KEY] = email
            avatarUrl?.let { prefs[AVATAR_URL_KEY] = it }
        }
    }

    suspend fun clearToken() {
        context.dataStore.edit { prefs ->
            prefs.remove(TOKEN_KEY)
            prefs.remove(EMAIL_KEY)
            prefs.remove(NAME_KEY)
            prefs.remove(AVATAR_URL_KEY)
            prefs.remove(USER_TYPE_KEY)
        }
    }
}
