package com.atridad.ascently.data.state

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import com.atridad.ascently.utils.AppLogger
import com.atridad.ascently.utils.DateFormatUtils

/**
 * Manages the overall data state timestamp for sync purposes. This tracks when any data in the
 * local database was last modified, independent of individual entity timestamps.
 */
class DataStateManager(context: Context) {

    companion object {
        private const val TAG = "DataStateManager"
        private const val PREFS_NAME = "ascently_data_state"
        private const val KEY_LAST_MODIFIED = "last_modified_timestamp"
        private const val KEY_INITIALIZED = "state_initialized"
    }

    private val prefs: SharedPreferences =
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

    init {
        if (!isInitialized()) {
            updateDataState()
            markAsInitialized()
            AppLogger.d(TAG) { "DataStateManager initialized with timestamp: ${getLastModified()}" }
        }
    }

    /**
     * Updates the data state timestamp to the current time. Call this whenever any data is modified
     * (create, update, delete).
     */
    fun updateDataState() {
        val now = DateFormatUtils.nowISO8601()
        prefs.edit { putString(KEY_LAST_MODIFIED, now) }
        AppLogger.d(TAG) { "Data state updated to: $now" }
    }

    /**
     * Gets the current data state timestamp. This represents when any data was last modified
     * locally.
     */
    fun getLastModified(): String {
        return prefs.getString(KEY_LAST_MODIFIED, DateFormatUtils.nowISO8601())
            ?: DateFormatUtils.nowISO8601()
    }

    /** Checks if the data state has been initialized. */
    private fun isInitialized(): Boolean {
        return prefs.getBoolean(KEY_INITIALIZED, false)
    }

    /** Marks the data state as initialized. */
    private fun markAsInitialized() {
        prefs.edit { putBoolean(KEY_INITIALIZED, true) }
    }
}
