import Foundation

enum DiskCache {
    private static var cacheDirectory: URL {
        FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
            .appendingPathComponent("ListCache", isDirectory: true)
    }

    private static func fileURL(for name: String) -> URL {
        cacheDirectory.appendingPathComponent(name).appendingPathExtension("json")
    }

    static func save(_ items: [some Codable], as name: String) {
        do {
            let dir = cacheDirectory
            if !FileManager.default.fileExists(atPath: dir.path) {
                try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
            }
            let data = try JSONEncoder().encode(items)
            try data.write(to: fileURL(for: name), options: .atomic)
        } catch {
            // Non-fatal
        }
    }

    static func load<T: Codable>(as name: String) -> [T]? {
        guard let data = try? Data(contentsOf: fileURL(for: name)),
              let items = try? JSONDecoder().decode([T].self, from: data),
              !items.isEmpty
        else { return nil }
        return items
    }

    static func removeAll() {
        try? FileManager.default.removeItem(at: cacheDirectory)
    }
}
