package com.crm.chat.worker

import android.content.Context
import androidx.work.*
import java.util.concurrent.TimeUnit

object BackgroundSyncManager {

    private const val SYNC_WORK_NAME = "background_sync_work"

    fun scheduleBackgroundSync(context: Context) {
        val workManager = WorkManager.getInstance(context)

        // Cancel any existing work
        workManager.cancelUniqueWork(SYNC_WORK_NAME)

        // Create constraints - only run when connected to network
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

        // Create periodic work request - run every 10 minutes
        val syncWorkRequest = PeriodicWorkRequestBuilder<BackgroundSyncWorker>(
            10, TimeUnit.MINUTES, // Repeat interval
            5, TimeUnit.MINUTES   // Flex interval
        )
            .setConstraints(constraints)
            .build()

        // Enqueue the work
        workManager.enqueueUniquePeriodicWork(
            SYNC_WORK_NAME,
            ExistingPeriodicWorkPolicy.UPDATE,
            syncWorkRequest
        )
    }

    fun cancelBackgroundSync(context: Context) {
        WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)
    }

    fun isBackgroundSyncScheduled(context: Context): Boolean {
        val workManager = WorkManager.getInstance(context)
        val workInfos = workManager.getWorkInfosForUniqueWork(SYNC_WORK_NAME).get()
        return workInfos.any { it.state == WorkInfo.State.ENQUEUED || it.state == WorkInfo.State.RUNNING }
    }
}
