package com.remax.notification.worker

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.remax.base.report.DataReportManager
import com.remax.notification.check.NotificationCheckController
import com.remax.notification.controller.NotificationTriggerController
import com.remax.notification.service.NotificationKeepAliveServiceManager
import com.remax.notification.timing.NotificationTimingController
import com.remax.notification.utils.NotiLogger
import com.remax.notification.utils.Topic
import kotlinx.coroutines.delay

/**
 * 通知保活 Worker
 * 用于定期检查并确保常驻通知存在
 */
class NotificationKeepAliveWorker(
    val context: Context,
    params: WorkerParameters
) : CoroutineWorker(context, params) {

    companion object {
        private const val TAG = "NotificationKeepAliveWorker"
        private const val WORK_NAME = "notification_keep_alive"
        
        /**
         * 创建保活工作请求
         * @param context 上下文
         * @return 工作请求
         */
        fun createWorkRequest(context: Context) {
            // 这里可以添加具体的 WorkManager 配置
            // 例如：周期性工作、约束条件等
            NotiLogger.d("创建通知保活工作请求")
        }
    }

    override suspend fun doWork(): Result {
        return try {
            NotiLogger.d("开始执行通知保活任务")
            
            // 检查并确保常驻通知存在
            NotificationKeepAliveServiceManager.startKeepAliveService(context = context,from = "workManager")

            // 尝试触发通知
            NotificationTimingController.getInstance().triggerNotificationIfAllowed(NotificationCheckController.NotificationType.KEEPALIVE)
            
            // 等待一段时间确保通知发送完成
            delay(1000)
            
            NotiLogger.d("通知保活任务执行完成")
            Result.success()
            
        } catch (e: Exception) {
            NotiLogger.e("通知保活任务执行失败", e)
            Result.failure()
        }
    }
}
