package ru.myitschool.work.data.repo

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 kotlinx.coroutines.flow.firstOrNull
import ru.myitschool.work.App
import ru.myitschool.work.data.AESEncyption
import ru.myitschool.work.data.dto.AuthRequestDto
import ru.myitschool.work.data.dto.AuthResponseDto
import ru.myitschool.work.data.source.NetworkDataSource

object AuthRepository {
    private const val STORE = "AUTH-STORE"
    private const val TOKEN_KEY = "TOKEN"

    private var tokenCache: String? = null

    suspend fun checkAndSave(login: String, password: String): Result<AuthResponseDto> {
        val data = AuthRequestDto(login=login, password=password)
        return NetworkDataSource.checkAuth(data).onSuccess { success ->
            val encryptedTokenCache = AESEncyption.encrypt(success.token)
            tokenCache = encryptedTokenCache
            if (encryptedTokenCache != null) {
                App.context.userDataStore.edit { preferences ->
                    val prefKey = stringPreferencesKey(TOKEN_KEY)
                    preferences[prefKey] = encryptedTokenCache
                }
            }
        }
    }

    suspend fun getToken(): String? {
        if (tokenCache == null) {
            tokenCache = App.context.userDataStore.data
                .firstOrNull()
                ?.let { preferences ->
                    preferences[stringPreferencesKey(TOKEN_KEY)]
                }
        }
        if (tokenCache != null) {
            return AESEncyption.decrypt(tokenCache)
        }
        return null
    }

    suspend fun logout() {
        tokenCache = null
        App.context.userDataStore.edit { preferences ->
            val prefKey = stringPreferencesKey(TOKEN_KEY)
            preferences.remove(prefKey)
        }
    }

    private val Context.userDataStore: DataStore<Preferences> by preferencesDataStore(name = STORE)
}