//
//  SDLApi.swift
//  sdlan
//
//  Created by 安礼成 on 2024/6/5.
//

import Foundation

struct SDLAPIResponse<T: Decodable>: Decodable {
    let code: Int
    let message: String?
    let data: T?
}

struct SDLAPIError: Error, Decodable {
    let code: Int
    let message: String
}

struct SDLAPIClient {
    
    static var baseUrl: String = "https://punchnet.s5s8.com/api"
    
    static func doPost<T: Decodable>(path: String, params: [String: Any], as: T.Type) async throws -> T {
        let postData = try! JSONSerialization.data(withJSONObject: params)
        var request = URLRequest(url: URL(string: baseUrl + path)!)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = postData
        
        let (data, _) = try await URLSession.shared.data(for: request)
        
        NSLog("response is: \(String(bytes: data, encoding: .utf8))")
        
        let apiResponse = try JSONDecoder().decode(SDLAPIResponse<T>.self, from: data)
        if apiResponse.code == 0, let data = apiResponse.data {
            return data
        } else if let message = apiResponse.message {
            throw SDLAPIError(code: apiResponse.code, message: message)
        } else {
            throw DecodingError.dataCorrupted(
                .init(
                    codingPath: [],
                    debugDescription: "Invalid JSON-RPC response: \(String(data: data, encoding: .utf8) ?? "")"
                )
            )
        }
    }
    
}
