package com.swoosh.microblog.data

import android.content.Context
import android.content.SharedPreferences

class NewsletterPreferences private constructor(
    private val prefs: SharedPreferences,
    private val accountIdProvider: () -> String
) {

    constructor(context: Context) : this(
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE),
        accountIdProvider = { AccountManager(context).getActiveAccount()?.id ?: "" }
    )

    /** Constructor for testing with plain SharedPreferences and a fixed account ID. */
    constructor(prefs: SharedPreferences, accountId: String) : this(
        prefs = prefs,
        accountIdProvider = { accountId }
    )

    private fun activeAccountId(): String = accountIdProvider()

    fun isNewsletterEnabled(): Boolean =
        prefs.getBoolean("newsletter_enabled_${activeAccountId()}", false)

    fun setNewsletterEnabled(enabled: Boolean) =
        prefs.edit().putBoolean("newsletter_enabled_${activeAccountId()}", enabled).apply()

    companion object {
        const val PREFS_NAME = "newsletter_prefs"
    }
}
