package com.example.shiftalarm

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat

class AlarmForegroundService : Service() {

    private val CHANNEL_ID = "SHIFT_ALARM_CHANNEL_V5"
    private val NOTIFICATION_ID = 1

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val shiftType = intent?.getStringExtra("EXTRA_SHIFT") ?: "근무"
        val soundUri = intent?.getStringExtra("EXTRA_SOUND")
        val snoozeMin = intent?.getIntExtra("EXTRA_SNOOZE", 5) ?: 5
        val snoozeRepeat = intent?.getIntExtra("EXTRA_SNOOZE_REPEAT", 3) ?: 3

        // 1. 알림 채널 생성
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "교대링 알람",
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "알람이 울리는 동안 표시되는 알림입니다."
                setSound(null, null) // 소리는 Activity에서 재생
                enableVibration(false) // 진동은 Activity에서 재생
            }
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
        }

        // 2. 전체화면 실행을 위한 PendingIntent
        val fullScreenIntent = Intent(this, AlarmActivity::class.java).apply {
            putExtra("EXTRA_SHIFT", shiftType)
            putExtra("EXTRA_SOUND", soundUri)
            putExtra("EXTRA_SNOOZE", snoozeMin)
            putExtra("EXTRA_SNOOZE_REPEAT", snoozeRepeat)
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        }
        
        val fullScreenPendingIntent = PendingIntent.getActivity(
            this,
            100,
            fullScreenIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        // 3. 일원화된 단일 알림 생성
        val contentText = if (shiftType == "SNOOZE") "다시 울림 알람입니다." else "오늘의 근무는 [$shiftType] 입니다."
        
        val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("교대링 알람 작동 중")
            .setContentText(contentText)
            .setSmallIcon(R.drawable.ic_alarm_blue)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setCategory(NotificationCompat.CATEGORY_ALARM)
            .setFullScreenIntent(fullScreenPendingIntent, true)
            .setContentIntent(fullScreenPendingIntent)
            .setOngoing(true)
            .setAutoCancel(false)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .build()

        // 4. Foreground 시작
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { // Android 14+
            startForeground(NOTIFICATION_ID, notification, android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
        } else {
            startForeground(NOTIFICATION_ID, notification)
        }

        return START_NOT_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null
}
