package com.github.nullptroma.wallenc.app.sync

import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import dagger.hilt.android.qualifiers.ApplicationContext
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class StorageSyncScheduler @Inject constructor(
    @param:ApplicationContext private val app: Context,
) {
    fun ensureScheduled() {
        val request = PeriodicWorkRequestBuilder<StorageSyncWorker>(
            repeatInterval = 30,
            repeatIntervalTimeUnit = TimeUnit.MINUTES,
        )
            .setConstraints(
                Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build(),
            )
            .build()

        // KEEP: UPDATE сбрасывает таймер periodic work при каждом onCreate процесса.
        WorkManager.getInstance(app).enqueueUniquePeriodicWork(
            StorageSyncWorker.UNIQUE_WORK_NAME,
            ExistingPeriodicWorkPolicy.KEEP,
            request,
        )
    }
}
