import Foundation

class GIFStorageService {
    static let shared = GIFStorageService()
    
    private let userDefaults = UserDefaults(suiteName: "group.gifcollector")
    private let savedGIFsKey = "savedGIFs"
    
    private init() {
        // Make sure the shared UserDefaults exists
        if userDefaults == nil {
            print("Error: Could not create UserDefaults with app group")
        }
    }
    
    func saveGIF(_ gif: GIF) {
        var savedGIFs = fetchGIFs()
        
        // Don't save duplicate URLs
        if !savedGIFs.contains(where: { $0.urlString == gif.urlString }) {
            savedGIFs.append(gif)
            saveToUserDefaults(gifs: savedGIFs)
        }
    }
    
    func fetchGIFs() -> [GIF] {
        guard let data = userDefaults?.data(forKey: savedGIFsKey),
              let gifs = try? JSONDecoder().decode([GIF].self, from: data) else {
            return []
        }
        
        return gifs.sorted(by: { $0.createdAt > $1.createdAt })
    }
    
    func deleteGIF(with id: UUID) {
        var savedGIFs = fetchGIFs()
        savedGIFs.removeAll(where: { $0.id == id })
        saveToUserDefaults(gifs: savedGIFs)
    }
    
    func clearAllGIFs() {
        saveToUserDefaults(gifs: [])
    }
    
    private func saveToUserDefaults(gifs: [GIF]) {
        guard let data = try? JSONEncoder().encode(gifs) else { return }
        userDefaults?.set(data, forKey: savedGIFsKey)
    }
}