package com.jihe.punchnet.data

import android.content.Context
import androidx.core.content.edit
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

object AppAuthRepository {
    private const val PREFS_NAME = "punchnet_app_auth"
    private const val KEY_ALLOWED_APPS = "allowed_apps"
    
    private val _allowedApps = MutableStateFlow<Set<String>>(emptySet())
    val allowedApps: StateFlow<Set<String>> = _allowedApps

    fun init(context: Context) {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        val savedApps = prefs.getStringSet(KEY_ALLOWED_APPS, emptySet()) ?: emptySet()
        _allowedApps.value = savedApps
    }

    fun toggleApp(context: Context, packageName: String, isAllowed: Boolean) {
        val current = _allowedApps.value.toMutableSet()
        if (isAllowed) {
            current.add(packageName)
        } else {
            current.remove(packageName)
        }
        _allowedApps.value = current
        
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        prefs.edit {
            putStringSet(KEY_ALLOWED_APPS, current)
        }
    }
}
