package com.jishisongfu.duobibi.util

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import com.jishisongfu.duobibi.MainActivity
import com.jishisongfu.duobibi.R
import com.jishisongfu.duobibi.data.db.AlertMode
import com.jishisongfu.duobibi.data.repo.AlertTriggered

/**
 * 降价提醒雷达本地通知。batchCheckAlerts 返回的 triggered 列表每条一条通知。
 *
 * 通知 ID = [Constants.ALERT_NOTIFICATION_ID_BASE] + alertId,同一条多次触发覆盖不堆积。
 * 点击跳回 MainActivity(SINGLE_TOP 复用现有实例,不进新栈)。
 */
object AlertNotifier {

    fun notifyTriggered(ctx: Context, triggered: List<AlertTriggered>) {
        if (triggered.isEmpty()) return
        val nm = ctx.getSystemService(NotificationManager::class.java) ?: return
        ensureChannel(nm, ctx)

        val openAppIntent = Intent(ctx, MainActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        }
        val openAppPi = PendingIntent.getActivity(
            ctx, 0, openAppIntent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
        )

        triggered.forEach { t ->
            val plat = t.platform?.takeIf { it.isNotBlank() } ?: "全网"
            val title: String
            val body: String
            if (t.mode == AlertMode.BOUGHT) {
                title = "💰 可申请价保!可省 ¥${fmt(t.savings)}"
                body = "${t.title} 在$plat 降到 ¥${fmt(t.currentPrice)}" +
                    "(买价 ¥${fmt(t.anchorPrice)}),点击查看"
            } else {
                title = "🎯 降到你的心理价啦!"
                body = "${t.title} 现已 ¥${fmt(t.currentPrice)}($plat)" +
                    ",心理价 ¥${fmt(t.anchorPrice)},点击查看"
            }
            val notif = NotificationCompat.Builder(ctx, Constants.ALERT_NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(body)
                .setStyle(NotificationCompat.BigTextStyle().bigText(body))
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(openAppPi)
                .build()
            nm.notify(Constants.ALERT_NOTIFICATION_ID_BASE + t.id.toInt(), notif)
        }
    }

    private fun ensureChannel(nm: NotificationManager, ctx: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            nm.createNotificationChannel(
                NotificationChannel(
                    Constants.ALERT_NOTIFICATION_CHANNEL_ID,
                    ctx.getString(R.string.alert_notification_channel),
                    NotificationManager.IMPORTANCE_HIGH,
                )
            )
        }
    }

    private fun fmt(p: Double): String =
        if (p == p.toLong().toDouble()) p.toLong().toString() else "%.2f".format(p)
}
