package com.safecheckin.app.service

import android.content.Context
import androidx.work.*
import com.safecheckin.app.data.repository.CloudRepository
import com.safecheckin.app.utils.NotificationHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit

/**
 * 定时检查 Worker v1
 * - 宽限期配置从云端获取（与服务器保持一致）
 * - 超时后发送本地预警通知（邮件由服务器自动发）
 * - 提前2小时发送提醒通知
 */
class CheckInWorker(
    context: Context,
    params: WorkerParameters
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        val context = applicationContext
        val repository = CloudRepository(context)

        return try {
            // 从云端获取宽限期配置
            val gracePeriod = repository.getGracePeriod()
            val gracePeriodMs = (gracePeriod.first.toLong() * 60 + gracePeriod.second) * 60 * 1000L

            // 从云端获取打卡记录，取最近一次打卡时间
            val userStats = repository.getUserStats()
            val lastCheckInStr = (userStats["last_check_in"] as? String) ?: ""

            val lastCheckInTime: Long = if (lastCheckInStr.isNotBlank()) {
                try {
                    val sdf = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
                    sdf.parse(lastCheckInStr)?.time ?: System.currentTimeMillis()
                } catch (e: Exception) {
                    System.currentTimeMillis()
                }
            } else {
                // 无打卡记录，视为刚才打卡，不触发预警
                System.currentTimeMillis()
            }

            val now = System.currentTimeMillis()
            val timeSinceLastCheckIn = now - lastCheckInTime

            when {
                timeSinceLastCheckIn > gracePeriodMs -> {
                    // 超过宽限期 — 发本地预警通知（邮件由服务器负责）
                    withContext(Dispatchers.Main) {
                        NotificationHelper.showWarningNotification(context)
                    }
                    Result.success()
                }
                gracePeriodMs > 2 * 3600000L && timeSinceLastCheckIn > gracePeriodMs - 2 * 3600000L -> {
                    // 宽限期超过2小时，且距结束不足2小时 — 发提醒通知
                    NotificationHelper.showReminderNotification(context)
                    Result.success()
                }
                else -> Result.success()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            // 网络失败时不重试（避免频繁请求），等下次定期调度
            Result.success()
        }
    }

    companion object {
        const val WORK_NAME = "check_in_worker"

        fun schedule(context: Context) {
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build()

            val checkInWork = PeriodicWorkRequestBuilder<CheckInWorker>(1, TimeUnit.HOURS)
                .setConstraints(constraints)
                .setInitialDelay(5, TimeUnit.MINUTES)
                .build()

            WorkManager.getInstance(context).enqueueUniquePeriodicWork(
                WORK_NAME,
                ExistingPeriodicWorkPolicy.KEEP,
                checkInWork
            )
        }

        fun cancel(context: Context) {
            WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
        }

        fun runOnce(context: Context) {
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build()
            WorkManager.getInstance(context).enqueue(
                OneTimeWorkRequestBuilder<CheckInWorker>().setConstraints(constraints).build()
            )
        }
    }
}
