import Foundation

/// 素材服务，处理与素材相关的网络请求
class MaterialService {
    
    /// 单例实例
    static let shared = MaterialService()
    
    private init() {}
    
    /// 上传素材信息
    /// - Parameters:
    ///   - fileId: 原文件ID
    ///   - previewFileId: 预览文件ID
    ///   - completion: 完成回调，返回是否成功
    func uploadMaterialInfo(fileId: String, 
                          previewFileId: String, 
                          completion: @escaping (Bool, String?) -> Void) {
        
        let materialData: [String: Any] = [
            "material": [
                "file_id": fileId,
                "preview_file_id": previewFileId
            ]
        ]
        
        guard let url = URL(string: "\(APIConfig.baseURL)/material") else {
            completion(false, "无效的URL")
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = APIConfig.authHeaders
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: materialData)
            
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                if let error = error {
                    completion(false, "上传失败: \(error.localizedDescription)")
                    return
                }
                
                if let httpResponse = response as? HTTPURLResponse {
                    if (200...299).contains(httpResponse.statusCode) {
                        completion(true, nil)
                    } else {
                        let statusCode = httpResponse.statusCode
                        let errorMessage = String(data: data ?? Data(), encoding: .utf8) ?? ""
                        completion(false, "服务器返回错误状态码: \(statusCode), 响应: \(errorMessage)")
                    }
                } else {
                    completion(false, "无效的服务器响应")
                }
            }
            
            task.resume()
            
        } catch {
            completion(false, "请求数据序列化失败: \(error.localizedDescription)")
        }
    }
}
