//
//  DataCleaner.swift
//  LotteryTracker
//
//  Created by aaa on 2026/1/22.
//

import Foundation
internal import CoreData

class DataCleaner {
    static func clearAllTickets(context: NSManagedObjectContext, completion: @escaping (Bool, String?) -> Void) {
        DispatchQueue.global(qos: .userInitiated).async {
            let fetchRequest: NSFetchRequest<NSFetchRequestResult> = LotteryTicket.fetchRequest()
            
            do {
                // 获取所有票券
                let tickets = try context.fetch(fetchRequest) as? [LotteryTicket] ?? []
                print("找到 \(tickets.count) 条记录需要删除")
                
                // 逐一删除
                for ticket in tickets {
                    context.delete(ticket)
                }
                
                // 保存更改
                if context.hasChanges {
                    try context.save()
                    print("✅ 保存删除操作")
                }
                
                // 重置上下文
                context.reset()
                
                DispatchQueue.main.async {
                    completion(true, nil)
                    print("✅ 数据清空完成")
                }
                
            } catch {
                DispatchQueue.main.async {
                    completion(false, "删除失败: \(error.localizedDescription)")
                    print("❌ 删除失败: \(error)")
                }
            }
        }
    }
}
