//
//  Persistence.swift
//  Gas Man
//
//  Created by Kameron Kenny on 3/17/25.
//

import CoreData

struct PersistenceController {
    static let shared = PersistenceController()
    
    let container: NSPersistentCloudKitContainer

    init(inMemory: Bool = false) {
        // "GasMan" must match the name of your .xcdatamodeld file.
        container = NSPersistentCloudKitContainer(name: "Gas_Man")

        
        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }
        
        // Enable CloudKit options if necessary
        guard let description = container.persistentStoreDescriptions.first else {
            fatalError("No persistent store description found.")
        }
        description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
        description.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.pro.thelinux.GasMan") // Update with your container ID
        
        container.loadPersistentStores { storeDescription, error in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        }
        
        // Automatically merge changes from iCloud
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}
