import Foundation
import UserNotifications
#if canImport(UIKit)
import UIKit
#endif

/// Manages local UNUserNotificationCenter notifications for download events.
@MainActor
final class NotificationManager {
    static let shared = NotificationManager()
    private init() {}

    /// Requests notification authorization the first time the app launches.
    /// Skips the system prompt if permission has already been granted or denied.
    func requestPermissionIfNeeded() async {
        let center = UNUserNotificationCenter.current()
        let settings = await center.notificationSettings()
        guard settings.authorizationStatus == .notDetermined else { return }
        _ = try? await center.requestAuthorization(options: [.alert, .sound])
    }

    /// Fires a local notification when a download fails.
    /// Suppressed while the app is in the foreground — an in-app alert already
    /// surfaces the error there, so a notification would be redundant.
    func sendDownloadFailedNotification(itemTitle: String) async {
        #if canImport(UIKit)
        guard UIApplication.shared.applicationState != .active else { return }
        #endif

        let content = UNMutableNotificationContent()
        content.title = "Download fehlgeschlagen"
        // \u{201E} = „  (DOUBLE LOW-9 QUOTATION MARK, German opening)
        // \u{201C} = "  (LEFT DOUBLE QUOTATION MARK, German closing)
        content.body = "\u{201E}\(itemTitle)\u{201C} konnte nicht heruntergeladen werden."
        content.sound = .default

        let request = UNNotificationRequest(
            identifier: "download-failed-\(UUID().uuidString)",
            content: content,
            trigger: nil  // deliver immediately
        )
        try? await UNUserNotificationCenter.current().add(request)
    }
}
