namespace Darkmatter.Libs.PlayerPrefs
{
    /// <summary>
    /// Tracks whether a local PlayerPrefs value has unsynced writes or clears.
    /// Prevents stale backend data from overwriting local state when the player
    /// was offline during a write or clear operation.
    ///
    /// Usage:
    ///   - Before any local write: MarkPendingWrite(key)
    ///   - Before any local clear: MarkPendingClear(key)
    ///   - After a confirmed backend success: MarkSynced(key)
    ///   - On load: check GetState(key) before deciding whether remote wins
    /// </summary>
    public static class LocalWriteTracker
    {
        public enum WriteState
        {
            Synced = 0,
            PendingWrite = 1,
            PendingClear = 2
        }

        private static string StateKey(string dataKey) => $"{dataKey}.__wstate";

        public static WriteState GetState(string key)
            => (WriteState)ProtectedPlayerPrefs.GetInt(StateKey(key), (int)WriteState.Synced);

        public static void MarkPendingWrite(string key)
        {
            ProtectedPlayerPrefs.SetInt(StateKey(key), (int)WriteState.PendingWrite);
            ProtectedPlayerPrefs.Save();
        }

        public static void MarkPendingClear(string key)
        {
            ProtectedPlayerPrefs.SetInt(StateKey(key), (int)WriteState.PendingClear);
            ProtectedPlayerPrefs.Save();
        }

        public static void MarkSynced(string key)
        {
            ProtectedPlayerPrefs.SetInt(StateKey(key), (int)WriteState.Synced);
            ProtectedPlayerPrefs.Save();
        }
    }
}
