import Foundation // 必须导入

struct LoginResponse: Codable {
    let token: String?
    let error: String?
}

func callLoginAPI() {
    // 1. 创建 URL
    let urlString = "http://192.168.31.156:31646/api/v1/iam/login/password-login"
    guard let url = URL(string: urlString) else {
        print("Invalid URL")
        return
    }
    
    // 2. 准备请求体
    let body = ["username": "testUser", "password": "test123"]
    guard let jsonData = try? JSONSerialization.data(withJSONObject: body) else {
        print("JSON encoding failed")
        return
    }
    print(jsonData)
    // 3. 配置请求
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData
    print(request)
    // 4. 发送请求
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            return
        }
        
        guard let data = data else {
            print("No data received")
            return
        }
        
        do {
            let result = try JSONDecoder().decode(LoginResponse.self, from: data)
            print("Token: \(result.token ?? "nil")")
        } catch {
            print("Decoding error: \(error)")
        }
    }
    task.resume()
}
