//
//  TinkAPIClient.swift
//  react-native-tink-sdk
//
//  Created by id856574 on 30/05/2024.
//

import Foundation

struct ApiResponse: Codable {
    let code: String
    // Add other properties that you expect in the response
}

func postAuthorizationGrant(clientAccessToken: String, userId: String, idHint: String, completion: @escaping (Result<ApiResponse, Error>) -> Void) {
    let urlString = "https://api.tink.com/api/v1/oauth/authorization-grant/delegate"
    guard let url = URL(string: urlString) else {
        print("Invalid URL")
        return
    }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("Bearer \(clientAccessToken)", forHTTPHeaderField: "Authorization")
    let bodyParameters = [
        "user_id": userId,
        "id_hint": idHint,
        "actor_client_id": "df05e4b379934cd09963197cc855bfe9",
        "scope": "authorization:read,authorization:grant,credentials:refresh,credentials:read,credentials:write,providers:read,user:read"
    ]
    
    request.httpBody = bodyParameters
        .map { "\($0.key)=\($0.value)" }
        .joined(separator: "&")
        .data(using: .utf8)

    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, httpResponse.statusCode == 200 else {
            let statusCodeError = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid response from server"])
            completion(.failure(statusCodeError))
            return
        }

        guard let data = data else {
            let dataError = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "No data received"])
            completion(.failure(dataError))
            return
        }

        do {
            let apiResponse = try JSONDecoder().decode(ApiResponse.self, from: data)
            completion(.success(apiResponse))
        } catch let decodeError {
            completion(.failure(decodeError))
        }
    }

    task.resume()
}
