import Foundation
import Combine

@MainActor
class AppUpdateService: ObservableObject {
    static let shared = AppUpdateService()
    @Published var updateAvailable = false
    @Published var latestVersion: String?

    private init() {}

    func checkForUpdate() {
        guard let bundleId = Bundle.main.bundleIdentifier else { return }
        let urlString = "https://itunes.apple.com/lookup?bundleId=\(bundleId)"
        guard let url = URL(string: urlString) else { return }

        Task {
            do {
                let (data, _) = try await URLSession.shared.data(from: url)
                guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
                      let results = json["results"] as? [[String: Any]],
                      let first = results.first,
                      let appStoreVersion = first["version"] as? String,
                      let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
                else { return }

                if appStoreVersion.compare(currentVersion, options: .numeric) == .orderedDescending {
                    self.updateAvailable = true
                    self.latestVersion = appStoreVersion
                }
            } catch {
                // silently fail
            }
        }
    }
}
