package com.seven.ikar.kotlin.core.push

import android.content.Context
import androidx.core.app.NotificationManagerCompat

object ChatNotificationDismissalManager {
    private const val PreferencesName = "ikar_chat_notifications"
    private const val ChatKeyPrefix = "chat:"
    private const val MaxTrackedNotificationsPerChat = 64

    fun recordChatNotification(context: Context, chatId: String?, notificationId: Int) {
        val normalizedChatId = chatId?.trim()?.takeIf { it.isNotBlank() } ?: return
        val preferences = context.applicationContext.getSharedPreferences(PreferencesName, Context.MODE_PRIVATE)
        val key = chatKey(normalizedChatId)
        val currentIds = preferences.getStringSet(key, emptySet()).orEmpty()
            .mapNotNull(String::toIntOrNull)
            .filterNot { it == notificationId }
        val nextIds = (currentIds + notificationId)
            .takeLast(MaxTrackedNotificationsPerChat)
            .map(Int::toString)
            .toSet()

        preferences.edit()
            .putStringSet(key, nextIds)
            .apply()
    }

    fun cancelChatNotifications(context: Context, chatId: String?) {
        val normalizedChatId = chatId?.trim()?.takeIf { it.isNotBlank() } ?: return
        val preferences = context.applicationContext.getSharedPreferences(PreferencesName, Context.MODE_PRIVATE)
        val key = chatKey(normalizedChatId)
        val notificationIds = preferences.getStringSet(key, emptySet()).orEmpty()
            .mapNotNull(String::toIntOrNull)

        if (notificationIds.isNotEmpty()) {
            val notificationManager = NotificationManagerCompat.from(context)
            notificationIds.forEach(notificationManager::cancel)
        }

        preferences.edit()
            .remove(key)
            .apply()
    }

    fun cancelNotification(context: Context, chatId: String?, notificationId: Int?) {
        if (notificationId != null) {
            NotificationManagerCompat.from(context).cancel(notificationId)
        }

        val normalizedChatId = chatId?.trim()?.takeIf { it.isNotBlank() } ?: return
        val resolvedNotificationId = notificationId ?: return
        val preferences = context.applicationContext.getSharedPreferences(PreferencesName, Context.MODE_PRIVATE)
        val key = chatKey(normalizedChatId)
        val nextIds = preferences.getStringSet(key, emptySet()).orEmpty()
            .mapNotNull(String::toIntOrNull)
            .filterNot { it == resolvedNotificationId }
            .map(Int::toString)
            .toSet()

        preferences.edit()
            .apply {
                if (nextIds.isEmpty()) {
                    remove(key)
                } else {
                    putStringSet(key, nextIds)
                }
            }
            .apply()
    }

    private fun chatKey(chatId: String): String = ChatKeyPrefix + chatId
}
