package com.example.shiftalarm

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class UpcomingAlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val alarmId = intent.getIntExtra("EXTRA_ALARM_ID", -1)
        val timeStr = intent.getStringExtra("EXTRA_TIME") ?: return
        val shiftType = intent.getStringExtra("EXTRA_SHIFT_TYPE") ?: "근무"
        val label = intent.getStringExtra("EXTRA_LABEL")
        val preAlarmMinutes = intent.getIntExtra("EXTRA_PRE_ALARM_MINUTES", 15)

        Log.d("UpcomingAlarmReceiver", "Received pre-alarm trigger for alarmId=$alarmId, time=$timeStr")

        // Check master alarm switch
        val prefs = context.getSharedPreferences("ShiftAlarmPrefs", Context.MODE_PRIVATE)
        if (!ShiftAlarmDefaults.isMasterAlarmEnabled(prefs)) {
            Log.d("UpcomingAlarmReceiver", "Master alarm disabled, skipping upcoming notification")
            return
        }

        CoroutineScope(Dispatchers.IO).launch {
            val db = AppDatabase.getDatabase(context)
            val alarms = db.shiftDao().getAllCustomAlarms()
            val alarm = alarms.find { it.id == alarmId || (it.time == timeStr && it.shiftType == shiftType) }

            if (alarm != null && alarm.isEnabled) {
                NotificationHelper.showUpcomingAlarmNotification(
                    context = context,
                    alarmId = alarm.id,
                    timeStr = timeStr,
                    shiftType = shiftType,
                    label = label,
                    minutesBefore = preAlarmMinutes
                )
            }
        }
    }
}
