//
//  NotificationFetcher.swift
//  MyHybridStarter
//
//  Created by Terrence Mahachi on 2025/10/24.
//  © 2025 gramiatechnologies. All rights reserved.
//

import Foundation
import UserNotifications

class NotificationFetcher {
    static let shared = NotificationFetcher()
    private let client = URLSession.shared

    // Cache the API base after first read
    lazy var apiBase: String = {
        return Self.readConfigJSON()?.apiBase ?? ""
    }()

    // -----------------------------------------------------------
    // MARK: - MAIN CHECK FUNCTION
    // -----------------------------------------------------------
    func checkForNotifications(completion: @escaping () -> Void) {
        let userId = UserDefaults.standard.string(forKey: "user_id")
        let institutionUserId = UserDefaults.standard.string(forKey: "institution_user_id")

        guard let userId = userId, let institutionUserId = institutionUserId else {
            print("⚠️ Missing user or institution_user ID — skipping fetch.")
            completion()
            return
        }

        // ✅ Build URL from config file
        let baseURL = apiBase.isEmpty ? "https://www.gramia.tech/public" : apiBase
        let endpoint = baseURL.hasSuffix("/") ? "\(baseURL)notification-count" : "\(baseURL)/notification-count"

        guard let url = URL(string: endpoint) else {
            print("❌ Invalid API URL:", endpoint)
            completion()
            return
        }

        print("🌍 Fetching notifications from:", url)

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        let body = "user=\(userId)&clear=true&institution_user=\(institutionUserId)&api=true"
        request.httpBody = body.data(using: .utf8)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        let task = client.dataTask(with: request) { data, response, error in
            defer { completion() }

            if let error = error {
                print("❌ Notification fetch failed:", error.localizedDescription)
                return
            }

            guard let data = data else {
                print("⚠️ Empty response data.")
                return
            }

            do {
                // ✅ Parse JSON properly
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    let title = json["title"] as? String ?? "Notification"
                    let count = json["count"] as? Int ?? 0

                    print("📨 Parsed notification JSON: \(title), count=\(count)")

                    if let records = json["records"] as? [[String: Any]], !records.isEmpty {
                        for record in records {
                            let recTitle = record["title"] as? String ?? "Notification"
                            let recMsg = record["message"] as? String ?? "You have a new message"
                            let recDate = record["reg_date"] as? String ?? ""
                            let recId = record["iD"] as? Int ?? 0

                            print("🔔 New Notification [\(recId)] \(recTitle): \(recMsg) @ \(recDate)")

                            // ✅ Show each record as its own notification
                            self.showNotification(title: recTitle, message: recMsg)
                        }
                    } else {
                        print("ℹ️ No records found in notification response.")
                    }
                } else {
                    print("⚠️ Could not parse JSON from notification response.")
                }

            } catch {
                print("❌ JSON parsing error:", error.localizedDescription)
                if let text = String(data: data, encoding: .utf8) {
                    print("🧾 Raw response:", text)
                }
            }
        }

        task.resume()
    }    // -----------------------------------------------------------
    // MARK: - LOCAL NOTIFICATION
    // -----------------------------------------------------------
    func showNotification(title: String, message: String) {
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = message
        content.sound = .default

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
        let request = UNNotificationRequest(
            identifier: UUID().uuidString,
            content: content,
            trigger: trigger
        )

        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

    // -----------------------------------------------------------
    // MARK: - CONFIG JSON READER
    // -----------------------------------------------------------
    static func readConfigJSON() -> (jsonString: String, apiBase: String)? {
        guard let url = Bundle.main.url(forResource: "app_config", withExtension: "json", subdirectory: "Config") else {
            print("❌ Could not find Config/app_config.json in bundle")
            return nil
        }

        do {
            let data = try Data(contentsOf: url)
            guard let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                print("❌ Invalid JSON structure in app_config.json")
                return nil
            }

            let rawBase = dict["API_BASE_URL"] as? String ?? ""
            let base = rawBase.trimmingCharacters(in: .whitespacesAndNewlines)
            let jsonStr = String(data: data, encoding: .utf8) ?? "{}"

            print("✅ Loaded app_config.json successfully. Base URL:", base)
            return (jsonStr, base)
        } catch {
            print("❌ Failed to read app_config.json:", error.localizedDescription)
            return nil
        }
    }
}
