import Combine
internal import CoreData
import Foundation

class PersistenceController: ObservableObject {
    // 单例模式
    static let shared = PersistenceController()
    
    // 预览实例
    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        
        // 添加预览数据
        for i in 0..<10 {
            let newTicket = LotteryTicket(context: viewContext)
            newTicket.id = UUID()
            newTicket.type = i % 2 == 0 ? "双色球" : "大乐透"
            newTicket.numbers = "预览号码 \(i)"
            newTicket.betCount = Int16(i % 3 + 1)
            newTicket.amount = Float(newTicket.betCount * 2)
            newTicket.date = Date().addingTimeInterval(Double(-i) * 86400)
            newTicket.drawDate = Date().addingTimeInterval(Double(i) * 86400)
            newTicket.status = i % 3 == 0 ? "待开奖" : (i % 3 == 1 ? "已中奖" : "未中奖")
            newTicket.prizeAmount = newTicket.status == "已中奖" ? newTicket.amount * 5 : 0
        }
        
        do {
            try viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("预览数据保存失败 \(nsError), \(nsError.userInfo)")
        }
        
        return result
    }()
    
    // Core Data 容器
    let container: NSPersistentContainer
    
    // 初始化
    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "LotteryTracker")
        
        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }
        
        container.loadPersistentStores { _, error in
            if let error = error {
                print("❌ Core Data 加载失败: \(error)")
            }
        }
        
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
    
    // 保存上下文
    func save() {
        let context = container.viewContext
        
        if context.hasChanges {
            do {
                try context.save()
                print("✅ 数据保存成功")
            } catch {
                print("❌ 数据保存失败: \(error)")
            }
        }
    }
}
