package com.seven.ikar.kotlin.core.session

import android.content.Context
import android.content.SharedPreferences
import com.seven.ikar.kotlin.core.model.AuthSessionDto
import kotlinx.serialization.json.Json

class SessionStore(context: Context, private val json: Json) {
    private val preferences: SharedPreferences =
        context.getSharedPreferences("ikar_kotlin_session", Context.MODE_PRIVATE)

    fun read(): AuthSessionDto? {
        val raw = preferences.getString(KEY_SESSION, null) ?: return null
        return runCatching { json.decodeFromString<AuthSessionDto>(raw) }.getOrNull()
    }

    fun save(session: AuthSessionDto) {
        preferences.edit()
            .putString(KEY_SESSION, json.encodeToString(AuthSessionDto.serializer(), session))
            .apply()
    }

    fun clear() {
        preferences.edit().remove(KEY_SESSION).apply()
    }

    companion object {
        private const val KEY_SESSION = "session"
    }
}
