//
//  See LICENSE folder for this template’s licensing information.
//
//  Abstract:
//  HTTP Send 

import Foundation

public class HTTPSend {
    private let url: URL
    
    public init(url: URL) {
        self.url = url
    }
    
    public func sendMessage(messageText: String, codeText: String, schoolId: String, completion: @escaping (Result<Void, Error>) -> Void) {
        let timestamp = Int(Date().timeIntervalSince1970) // 現在のタイムスタンプを生成
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let body: [String: Any] = [
            "message": messageText,
            "codetext": codeText,
            "timestamp": timestamp,
            "schoolId": schoolId
        ]
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
        } catch {
            completion(.failure(error))
            return
        }
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                completion(.failure(error))
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                //let statusError = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid response from server"])
                //completion(.failure(statusError))
                return
            }
            
            completion(.success(()))
        }
        task.resume()
    }
}
