//
//  CoreManger.swift
//  DouShouQi_App
//
//  Created by étudiant on 14/06/2024.
//

import Foundation
import CoreData
import DouShouQiModel
import Combine

class CoreDataManager {
    static let shared = CoreDataManager()
    private init() {}

    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "DouShouQi_App") // Remplacez par le nom de votre modèle
        container.loadPersistentStores { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        }
        return container
    }()

    var context: NSManagedObjectContext {
        return persistentContainer.viewContext
    }

    func saveContext() {
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

    func savePlayer(playerVM: PlayerVM) {
        let player = CDPlayer(context: context)
        player.name = playerVM.player.name
        player.photo = playerVM.player.photo
        saveContext()
    }

    func fetchPlayers() -> [CDPlayer] {
        let fetchRequest: NSFetchRequest<CDPlayer> = CDPlayer.fetchRequest()
        do {
            return try context.fetch(fetchRequest)
        } catch {
            print("Failed to fetch players: \(error)")
            return []
        }
    }
}
