package com.syncflow.worker

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.WorkManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import com.syncflow.data.db.SyncPairDao
import com.syncflow.domain.model.ScheduleType
import javax.inject.Inject

@AndroidEntryPoint
class BootReceiver : BroadcastReceiver() {
    @Inject lateinit var syncPairDao: SyncPairDao

    override fun onReceive(context: Context, intent: Intent) {
        val validActions = setOf(Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED)
        if (intent.action !in validActions) return
        val wm = WorkManager.getInstance(context)
        val pending = goAsync()
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val pairs = syncPairDao.getEnabled()
                var hasOnChange = false
                pairs.forEach { pair ->
                    when (pair.scheduleType) {
                        ScheduleType.ON_CHANGE -> hasOnChange = true
                        ScheduleType.MANUAL -> { /* nothing */ }
                        else -> {
                            val req = SyncWorker.buildPeriodicRequest(
                                pair.id,
                                pair.scheduleIntervalMinutes.toLong().coerceAtLeast(15),
                                pair.wifiOnly,
                                pair.chargingOnly,
                            )
                            wm.enqueueUniquePeriodicWork("periodic_${pair.id}", ExistingPeriodicWorkPolicy.UPDATE, req)
                        }
                    }
                }
                if (hasOnChange) FileWatchService.start(context)
            } finally {
                pending.finish()
            }
        }
    }
}
