//
//  CodableHelper.swift

//
//  Created by Leon on 2025/7/13.
//

import Foundation

enum CodableHelper {

    static func decode<T: Decodable>(_ type: T.Type, from data: Data) -> T? {
        //try? JSONDecoder().decode(T.self, from: data)
        do {
            return try JSONDecoder().decode(T.self, from: data)
        } catch {
            dlog("❌ 解码失败: \(error)")
            return nil
        }
    }

    static func decode<T: Decodable>(_ type: T.Type, from jsonString: String) -> T? {
        guard jsonString.count > 0 else{
            // dlog("⚠️jsonString is empty")
            return nil
        }
        guard let data = jsonString.data(using: .utf8) else { return nil }
        return decode(type, from: data)
    }
    
    static func decode<T: Decodable>(_ type: T.Type, from dictionary: [String: Any]) -> T? {
        guard let data = try? JSONSerialization.data(withJSONObject: dictionary) else { return nil }
        return decode(type, from: data)
    }

    static func encode<T: Encodable>(_ model: T) -> Data? {
        try? JSONEncoder().encode(model)
    }

    static func encodeToJSONString<T: Encodable>(_ model: T) -> String? {
        guard let data = encode(model) else { return nil }
        return String(data: data, encoding: .utf8)
    }

    static func printJSON<T: Encodable>(_ model: T) {
        if let json = encodeToJSONString(model) {
            print(json)
        } else {
            print("⚠️ Encode to JSON failed")
        }
    }
    
    static func jsonString(from data: Data) -> String? {
        String(data: data, encoding: .utf8)
    }
}
