import type { MergedNotificationSettings } from '@/lib/notifications/notificationSettingCatalog'
import { resolveNotificationSettingId } from '@/lib/notifications/notificationSettingCatalog'

const CACHE_KEY = 'gp_live_notification_settings_v1'

export function readNotificationSettingsCache(): MergedNotificationSettings | null {
    if (typeof window === 'undefined') return null
    try {
        const raw = localStorage.getItem(CACHE_KEY)
        if (!raw) return null
        return JSON.parse(raw) as MergedNotificationSettings
    } catch {
        return null
    }
}

export function writeNotificationSettingsCache(data: MergedNotificationSettings): void {
    if (typeof window === 'undefined') return
    try {
        localStorage.setItem(CACHE_KEY, JSON.stringify(data))
    } catch {
        // ignore quota errors
    }
}

export function shouldShowDesktopPushForType(
    notificationType: string,
    cache: MergedNotificationSettings | null
): boolean {
    if (!cache?.desktopNotificationEnabled) return false
    const settingId = resolveNotificationSettingId(notificationType)
    if (!settingId) return true
    const item = cache.settings.find((s) => s.id === settingId)
    return item?.pushEnabled ?? false
}
