//
//  CloudConvert.swift
//  Padel Tournament
//
//  Created by Razmig Sarkissian on 14/09/2023.
//

import Foundation

class CloudConvert {
    
    enum CloudConvertionError: LocalizedError {
        case unknownError
        case serviceError(ErrorResponse)
        case urlNotFound(String)
        
        var errorDescription: String? {
            switch self {
            case .unknownError:
                return "Erreur"
            case .serviceError(let errorResponse):
                return errorResponse.error
            case .urlNotFound(let url):
                return "L'URL [\(url)] n'est pas valide"
            }
        }
    }
    
    static let manager = CloudConvert()
    
    func uploadFile(_ url: URL) async throws -> String {
        return try await createJob(url)
    }
    
    func createJob(_ url: URL) async throws -> String {
        let apiPath = "https://\(URLs.activationHost.rawValue)/utils/xls-to-csv/"
        guard let taskURL = URL(string: apiPath) else {
            throw CloudConvertionError.urlNotFound(apiPath)
        }
        var request: URLRequest = URLRequest(url: taskURL)
        request.httpMethod = "POST"
        
        // Create the boundary string for multipart/form-data
        let boundary = UUID().uuidString
        
        // Set the content type to multipart/form-data with the boundary
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        // The file to upload
        let fileName = url.lastPathComponent
        let fileURL = url
        
        // Construct the body of the request
        var body = Data()
        
        // Start the body with the boundary and content-disposition for the file
        body.append("--\(boundary)\r\n".data(using: .utf8)!)
        body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
        body.append("Content-Type: application/vnd.ms-excel\r\n\r\n".data(using: .utf8)!)
        
        // Append the file data
        if let fileData = try? Data(contentsOf: fileURL) {
            body.append(fileData)
        }
        
        // End the body with the boundary
        body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
        
        // Set the body of the request
        request.httpBody = body
        
        let (data, response) = try await URLSession.shared.data(for: request)
        
        // Check the response status code
        if let httpResponse = response as? HTTPURLResponse {
            print("Status code: \(httpResponse.statusCode)")
        }
        
        // Convert the response data to a String
        if let responseString = String(data: data, encoding: .utf8) {
            return responseString
        } else {
            let error = ErrorResponse(code: 1, status: "Encodage", error: "Encodage des données de classement invalide")
            throw CloudConvertionError.serviceError(error)
        }
    }
}

// MARK: - ErrorResponse
struct ErrorResponse: Decodable {
    let code: Int
    let status, error: String
}
