// Copyright (C) 2026 Jason M. Schwefel. All Rights Reserved.
package com.coldboreballisticsllc.scopedope.ui.crash

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.coldboreballisticsllc.scopedope.data.crash.CrashReportingController
import com.coldboreballisticsllc.scopedope.data.prefs.AppPreferences
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Shared consent state for crash reporting (SPEC §16.1), used by both the first-run
 * consent dialog and the Settings → Privacy toggle so they stay in sync.
 *
 * Opt-in, OFF by default: nothing is enabled until the user explicitly chooses to.
 * Toggling here drives [CrashReportingController.enable]/[disable] immediately so the
 * runtime state always matches the persisted preference.
 */
@HiltViewModel
class CrashConsentViewModel @Inject constructor(
    private val prefs: AppPreferences,
    private val crashReporting: CrashReportingController,
) : ViewModel() {

    /** Current opt-in state (persisted). Default false. */
    val enabled: StateFlow<Boolean> = prefs.crashReportingEnabled
        .stateIn(viewModelScope, SharingStarted.Eagerly, false)

    /** Whether the one-time first-run consent prompt still needs to be shown. */
    val promptShown: StateFlow<Boolean> = prefs.crashReportingPromptShown
        .stateIn(viewModelScope, SharingStarted.Eagerly, true) // assume shown until disk read

    /**
     * Apply the user's consent choice: persist it and start/stop the reporter.
     * Used by both the first-run dialog (Allow/Not now) and the Settings toggle.
     */
    fun setEnabled(value: Boolean) {
        viewModelScope.launch {
            prefs.setCrashReportingEnabled(value)
            if (value) crashReporting.enable() else crashReporting.disable()
        }
    }

    /** Record that the first-run prompt has been shown so it never appears again. */
    fun markPromptShown() {
        viewModelScope.launch { prefs.setCrashReportingPromptShown() }
    }

    /**
     * Re-sync the reporter to the persisted preference at app start. Safe to call every
     * launch: if the user previously opted in, this re-enables; otherwise it stays off.
     */
    fun syncOnLaunch() {
        viewModelScope.launch {
            if (prefs.crashReportingEnabled.first()) crashReporting.enable()
        }
    }
}
