package com.tomhempel.rbarometer.notification

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log

object UploadReminderScheduler {

    private const val TAG = "UploadReminder"
    private const val DELAY_MS = 2 * 60 * 60 * 1000L   // 2 hours

    /**
     * Schedule (or re-schedule) a reminder alarm for 2 hours from now.
     * Call this every time a questionnaire is marked as completed.
     * Safe to call multiple times — replaces any existing alarm.
     */
    fun schedule(context: Context) {
        val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return
        val triggerAt = System.currentTimeMillis() + DELAY_MS

        // On API 31+ we need canScheduleExactAlarms(); fall back to inexact if not granted
        val pi = buildPendingIntent(context)
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
                alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAt, pi)
                Log.d(TAG, "Inexact alarm scheduled (no SCHEDULE_EXACT_ALARM permission)")
            } else {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pi)
                Log.d(TAG, "Exact alarm scheduled for +2h")
            }
        } catch (e: SecurityException) {
            Log.w(TAG, "Could not schedule alarm: ${e.message}")
        }
    }

    /**
     * Cancel any pending upload reminder. Call after a successful upload.
     */
    fun cancel(context: Context) {
        val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return
        alarmManager.cancel(buildPendingIntent(context))
        Log.d(TAG, "Alarm cancelled")
    }

    /**
     * Returns true if any assigned client has upload-ready pending work
     * (current session fully complete when applicable).
     */
    suspend fun hasPendingUploads(context: Context): Boolean {
        return try {
            com.tomhempel.rbarometer.data.PendingUploadRepository.hasUploadReady(context)
        } catch (e: Exception) {
            Log.w(TAG, "hasPendingUploads check failed: ${e.message}")
            false
        }
    }

    private fun buildPendingIntent(context: Context): PendingIntent {
        val intent = Intent(context, UploadReminderReceiver::class.java)
        return PendingIntent.getBroadcast(
            context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
    }
}
