//
//  AppDelegate.swift
//  Cable
//
//  Created by Stefan Lange-Hegermann on 01.11.25.
//


import Foundation
import UIKit
import Aptabase

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        Aptabase.shared.initialize(
            appKey: "A-SH-4260269603",
            with: InitOptions(host: "https://apta.yuzuhub.com")
        )
        let isFirstLaunch = !UserDefaults.standard.bool(forKey: "hasLaunchedBefore")
        if isFirstLaunch {
            UserDefaults.standard.set(true, forKey: "hasLaunchedBefore")
            AnalyticsTracker.log("First Launch")
        }
        AnalyticsTracker.log("App Launched")
        return true
    }
}

enum AnalyticsTracker {
    static func configure() {}

    static func log(_ event: String, properties: [String: Any] = [:]) {
        var converted: [String: Any] = [:]
        for (key, value) in properties {
            switch value {
            case let s as String: converted[key] = s
            case let i as Int: converted[key] = i
            case let d as Double: converted[key] = d
            case let f as Float: converted[key] = f
            case let b as Bool: converted[key] = b
            default: converted[key] = "\(value)"
            }
        }
        Aptabase.shared.trackEvent(event, with: converted)
#if DEBUG
        if properties.isEmpty {
            NSLog("Analytics: %@", event)
        } else {
            let formatted = properties
                .map { "\($0.key)=\($0.value)" }
                .sorted()
                .joined(separator: ", ")
            NSLog("Analytics: %@ { %@ }", event, formatted)
        }
#endif
    }
}
