package com.devlab.app.util

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

private val Context.dataStore by preferencesDataStore(name = "servermanager_prefs")

class PreferencesManager(private val context: Context) {

    companion object {
        private val KEY_TOKEN = stringPreferencesKey("api_token")
        private val KEY_USERNAME = stringPreferencesKey("username")
        private val KEY_EMAIL = stringPreferencesKey("email")
        private val KEY_ROLE = stringPreferencesKey("role")
        private val KEY_USER_ID = intPreferencesKey("user_id")
        private val KEY_LAST_NOTIFICATION_CHECK = longPreferencesKey("last_notification_check")
    }

    val token: Flow<String> = context.dataStore.data.map { prefs ->
        prefs[KEY_TOKEN] ?: ""
    }

    val username: Flow<String> = context.dataStore.data.map { prefs ->
        prefs[KEY_USERNAME] ?: ""
    }

    val email: Flow<String> = context.dataStore.data.map { prefs ->
        prefs[KEY_EMAIL] ?: ""
    }

    val role: Flow<String> = context.dataStore.data.map { prefs ->
        prefs[KEY_ROLE] ?: ""
    }

    val userId: Flow<Int> = context.dataStore.data.map { prefs ->
        prefs[KEY_USER_ID] ?: 0
    }

    suspend fun saveCredentials(token: String, username: String) {
        context.dataStore.edit { prefs ->
            prefs[KEY_TOKEN] = token
            prefs[KEY_USERNAME] = username
        }
    }

    suspend fun saveUserData(token: String, id: Int, username: String, email: String, role: String) {
        context.dataStore.edit { prefs ->
            prefs[KEY_TOKEN] = token
            prefs[KEY_USER_ID] = id
            prefs[KEY_USERNAME] = username
            prefs[KEY_EMAIL] = email
            prefs[KEY_ROLE] = role
        }
    }

    suspend fun saveProfile(email: String) {
        context.dataStore.edit { prefs ->
            prefs[KEY_EMAIL] = email
        }
    }

    suspend fun getToken(): String = context.dataStore.data.first()[KEY_TOKEN] ?: ""
    suspend fun getUsername(): String = context.dataStore.data.first()[KEY_USERNAME] ?: ""
    suspend fun getEmail(): String = context.dataStore.data.first()[KEY_EMAIL] ?: ""

    suspend fun getLastNotificationCheck(): Long {
        return context.dataStore.data.first()[KEY_LAST_NOTIFICATION_CHECK] ?: 0L
    }

    suspend fun setLastNotificationCheck(time: Long) {
        context.dataStore.edit { prefs ->
            prefs[KEY_LAST_NOTIFICATION_CHECK] = time
        }
    }

    suspend fun clear() {
        context.dataStore.edit { it.clear() }
    }
}
