package dev.privacyllc.period.feature.export

import android.content.Context
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.StateFlow
import java.time.Clock
import java.time.LocalDate
import javax.inject.Inject

/**
 * Thin on purpose.
 *
 * It asks for a picker and reads the outcome; it holds nothing. Everything that
 * has to survive leaving the app — the chosen destination, the result — lives in
 * `ExportController`, because returning from the picker can re-lock the app and
 * a re-lock clears every nav-scoped ViewModel, including this one.
 */
@HiltViewModel
class ExportViewModel @Inject constructor(
    private val controller: ExportController,
    private val exporter: DataExporter,
    private val clock: Clock,
) : ViewModel() {

    val outcome: StateFlow<ExportOutcome> = controller.outcome

    /** Non-null while a chosen destination is waiting to be written. */
    val destination = controller.destination

    fun begin() {
        controller.requestPicker(ExportCopy.fileName(LocalDate.now(clock)))
    }

    /**
     * Write the destination the user picked, now that the session is unlocked.
     *
     * Called only from inside the gate's unlocked branch. Writing while locked
     * would hand the whole history to somebody who took the phone during the
     * save dialog — the one window in this feature where the lock could be
     * walked around.
     */
    fun writePendingExport(context: Context) {
        val uri = controller.takeDestination() ?: return
        exporter.export(context.applicationContext, uri)
    }

    fun acknowledge() = controller.acknowledge()
}
