import UserNotifications

/// Joint la photo du produit (URL dans « image ») aux notifications push.
class NotificationService: UNNotificationServiceExtension {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttempt: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest,
                             withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttempt = request.content.mutableCopy() as? UNMutableNotificationContent

        let info = request.content.userInfo
        let urlString = (info["image"] as? String)
            ?? (info["fcm_options"] as? [String: Any])?["image"] as? String

        guard let content = bestAttempt,
              let urlString = urlString,
              let url = URL(string: urlString) else {
            contentHandler(request.content)
            return
        }

        URLSession.shared.downloadTask(with: url) { location, response, _ in
            defer { contentHandler(content) }
            guard let location = location else { return }

            let mime = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Type") ?? ""
            let ext = mime.contains("png") ? "png" : (mime.contains("webp") ? "webp" : "jpg")
            let tmp = URL(fileURLWithPath: NSTemporaryDirectory())
                .appendingPathComponent(UUID().uuidString + "." + ext)

            do {
                try FileManager.default.moveItem(at: location, to: tmp)
                let attachment = try UNNotificationAttachment(identifier: "product-image", url: tmp)
                content.attachments = [attachment]
            } catch {
                // Pas d'image : la notification reste affichée en texte seul.
            }
        }.resume()
    }

    override func serviceExtensionTimeWillExpire() {
        if let content = bestAttempt {
            contentHandler?(content)
        }
    }
}
