package eu.mhsl.marianum.mobile.client.widgets

import android.content.Context
import androidx.work.Constraints
import androidx.work.Data
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import dev.fluttercommunity.workmanager.BackgroundWorker

/**
 * Enqueues the app's Dart one-off widget refresh from native code, so a
 * freshly placed widget populates within seconds instead of waiting for the
 * next periodic slot.
 *
 * DART_TASK_KEY is public plugin API but no semver guarantee — re-verify on
 * workmanager upgrades. The Dart callback handle comes from SharedPreferences
 * persisted by Workmanager().initialize(); if the app never ran, the worker
 * fails gracefully and the widget keeps rendering its cached/empty state.
 */
object WidgetRefreshRequester {
    // Mirrors WidgetBackgroundTask.oneOffTaskName on the Dart side.
    private const val DART_ONE_OFF_TASK = "eu.mhsl.marianum.widget.refresh.once"

    fun enqueueOneOffRefresh(context: Context) {
        val request = OneTimeWorkRequest.Builder(BackgroundWorker::class.java)
            .setInputData(
                Data.Builder()
                    .putString(BackgroundWorker.DART_TASK_KEY, DART_ONE_OFF_TASK)
                    .build(),
            )
            .setConstraints(
                Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build(),
            )
            .build()
        WorkManager.getInstance(context).enqueue(request)
    }
}
