//
//  CableApp.swift
//  Cable
//
//  Created by Stefan Lange-Hegermann on 11.09.25.
//

import SwiftUI
import SwiftData

@main
struct CableApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
    @StateObject private var unitSettings = UnitSystemSettings()

    var sharedModelContainer: ModelContainer = {
        do {
            // Try the simple approach first
            return try ModelContainer(for: ElectricalSystem.self, SavedLoad.self, SavedBattery.self, SavedCharger.self, Item.self)
        } catch {
            print("Failed to create ModelContainer with simple approach: \(error)")

            // Try in-memory as fallback
            do {
                let schema = Schema([ElectricalSystem.self, SavedLoad.self, SavedBattery.self, SavedCharger.self, Item.self])
                let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
                return try ModelContainer(for: schema, configurations: [modelConfiguration])
            } catch {
                fatalError("Could not create even in-memory ModelContainer: \(error)")
            }
        }
    }()

    init() {
#if DEBUG
        UITestSampleData.handleLaunchArguments(container: sharedModelContainer)
#endif
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(unitSettings)
        }
        .modelContainer(sharedModelContainer)
    }
}
