package com.aletheia.app.data

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

class SettingsRepository(
    context: Context,
    private val databaseHelper: AppDatabaseHelper
) {
    private val securePrefs: SharedPreferences =
        context.getSharedPreferences(PASSWORD_PREFS, Context.MODE_PRIVATE)

    fun getString(key: String, defaultValue: String = ""): String =
        databaseHelper.getSetting(key) ?: defaultValue

    fun setString(key: String, value: String) {
        databaseHelper.setSetting(key, value)
    }

    fun getInt(key: String, defaultValue: Int = 0): Int =
        databaseHelper.getSetting(key)?.toIntOrNull() ?: defaultValue

    fun setInt(key: String, value: Int) {
        databaseHelper.setSetting(key, value.toString())
    }

    fun getDouble(key: String, defaultValue: Double = 0.0): Double =
        databaseHelper.getSetting(key)?.toDoubleOrNull() ?: defaultValue

    fun setDouble(key: String, value: Double) {
        databaseHelper.setSetting(key, value.toString())
    }

    fun getBoolean(key: String, defaultValue: Boolean = false): Boolean =
        databaseHelper.getSetting(key)?.toBooleanStrictOrNull() ?: defaultValue

    fun setBoolean(key: String, value: Boolean) {
        databaseHelper.setSetting(key, value.toString())
    }

    fun setAll(values: Map<String, String>) {
        databaseHelper.setSettings(values)
    }

    fun getAll(keys: Collection<String>): Map<String, String> = databaseHelper.getSettings(keys)

    fun getSecurePassword(): String =
        securePrefs.getString(
            KEY_QBOOKS_PASSWORD,
            securePrefs.getString(KEY_LEGACY_CATALOG_PASSWORD, "") ?: ""
        ) ?: ""

    fun setSecurePassword(password: String) {
        securePrefs.edit().putString(KEY_QBOOKS_PASSWORD, password).apply()
    }

    fun getCatalogUrl(): String {
        val configured = databaseHelper.getSetting(KEY_QBOOKS_URL)
            ?: databaseHelper.getSetting(KEY_LEGACY_CATALOG_URL)
        return resolveCatalogUrl(configured)
    }

    companion object {
        const val KEY_QBOOKS_URL = "QBooksUrl"
        const val KEY_QBOOKS_USERNAME = "QBooksUsername"
        const val KEY_LEGACY_CATALOG_URL = "CalibreUrl"
        const val KEY_LEGACY_CATALOG_USERNAME = "CalibreUsername"
        const val KEY_DEFAULT_FONT_SIZE = "DefaultFontSize"
        const val KEY_DEFAULT_FONT_FAMILY = "DefaultFontFamily"
        const val KEY_THEME = "Theme"
        const val KEY_BRIGHTNESS = "Brightness"
        const val KEY_READER_LINE_HEIGHT = "ReaderLineHeight"
        const val KEY_READER_MARGIN = "ReaderMargin"
        const val KEY_READER_ALIGNMENT = "ReaderAlignment"
        const val KEY_READER_VERTICAL_SCROLL = "ReaderVerticalScroll"
        const val KEY_READER_PAGE_TURN_MODE = "ReaderPageTurnMode"
        const val KEY_READER_INVERT_ZONES = "ReaderInvertZones"
        const val KEY_READER_BRIGHTNESS_GESTURE = "ReaderBrightnessGesture"
        const val KEY_READER_SYSTEM_BRIGHTNESS = "ReaderSystemBrightness"
        const val KEY_READER_ORIENTATION = "ReaderOrientation"
        const val KEY_READER_VOLUME_BUTTONS = "ReaderVolumeButtons"
        const val KEY_READER_KEEP_SCREEN_ON = "ReaderKeepScreenOn"
        const val KEY_READER_SHOW_TITLE = "ReaderShowTitle"
        const val KEY_READER_SHOW_STATUS = "ReaderShowStatus"
        const val DEFAULT_CATALOG_URL = "http://m.flibusta.is/opds"

        internal fun resolveCatalogUrl(configured: String?): String {
            val normalized = configured.orEmpty().trim().trimEnd('/')
            return if (
                normalized.isBlank() ||
                normalized.equals(LEGACY_QBOOKS_URL, ignoreCase = true) ||
                normalized.equals(LEGACY_HTTPS_CATALOG_URL, ignoreCase = true)
            ) {
                DEFAULT_CATALOG_URL
            } else {
                normalized
            }
        }

        private const val PASSWORD_PREFS = "aletheia_passwords"
        private const val KEY_QBOOKS_PASSWORD = "qbooks_password_secure"
        private const val KEY_LEGACY_CATALOG_PASSWORD = "calibre_password_secure"
        private const val LEGACY_QBOOKS_URL = "https://qbooks.kusoft.xyz"
        private const val LEGACY_HTTPS_CATALOG_URL = "https://m.flibusta.is/opds"
    }
}
