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

import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.github.nullptroma.wallenc.domain.tasks.StorageSyncTriggerReason
import com.github.nullptroma.wallenc.usecases.RunStorageSyncUseCase
import com.github.nullptroma.wallenc.usecases.StorageSyncRunOutcome
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import timber.log.Timber

@HiltWorker
class StorageSyncWorker @AssistedInject constructor(
    @Assisted appContext: Context,
    @Assisted params: WorkerParameters,
    private val syncRunner: RunStorageSyncUseCase,
) : CoroutineWorker(appContext, params) {

    override suspend fun doWork(): Result {
        Timber.d("Periodic storage sync started (attempt %d)", runAttemptCount)
        return when (val outcome = syncRunner.enqueueAndAwait(StorageSyncTriggerReason.Background)) {
            StorageSyncRunOutcome.SkippedAlreadyRunning -> {
                Timber.d("Periodic storage sync skipped — already running")
                Result.success()
            }
            StorageSyncRunOutcome.Completed -> {
                Timber.d("Periodic storage sync finished")
                Result.success()
            }
            StorageSyncRunOutcome.Cancelled -> {
                Timber.d("Periodic storage sync cancelled")
                Result.success()
            }
            is StorageSyncRunOutcome.Failed -> {
                Timber.w(outcome.error, "Periodic storage sync failed")
                Result.retry()
            }
        }
    }

    companion object {
        const val UNIQUE_WORK_NAME = "wallenc-storage-sync-periodic"
    }
}
