//
//  ChatGptManager.swift
//  WoWonder
//
//  Created by iMac on 10/06/25.
//  Copyright © 2025 ScriptSun. All rights reserved.
//

import Foundation
import Alamofire
import WowonderMessengerSDK

class ChatGptManager {
    
    static let instance = ChatGptManager()
    
    func getChatSuggestion(token: String, userMessage: String, completionBlock: @escaping (_ Success: ChatGptModel?, _ AuthError: ChatGptErrorModel?, Error?) -> () ) {
        let params = [
            "model": "gpt-3.5-turbo",
            "messages": [
                ["role": "system", "content": "Suggested messages to reply to the message sent"],
                ["role": "user", "content": userMessage]
            ]
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = "https://api.openai.com/v1/chat/completions"
        print("urlString >>>>> ", urlString)
        let headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Authorization": "Bearer \(token)"
        ]
        AF.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                if response.response?.statusCode == 200 {
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(ChatGptModel.self, from: data)
                    completionBlock(result, nil, nil)
                } else {
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(ChatGptErrorModel.self, from: data)
                    completionBlock(nil, result, nil)
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, response.error)
            }
        }
    }
    
    func generateText(token: String, userMessage: String, completionBlock: @escaping (_ Success: ChatGptModel?, _ AuthError: ChatGptErrorModel?, Error?) -> () ) {
        let params = [
            "model": "gpt-3.5-turbo",
            "messages": [
                ["role": "user", "content": userMessage]
            ]
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = "https://api.openai.com/v1/chat/completions"
        print("urlString >>>>>", urlString)
        let headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Authorization": "Bearer \(token)"
        ]
        AF.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                if response.response?.statusCode == 200 {
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(ChatGptModel.self, from: data)
                    completionBlock(result, nil, nil)
                } else {
                    if let error = res["error"] {
                        let data = try! JSONSerialization.data(withJSONObject: error, options: [])
                        let result = try! JSONDecoder().decode(ChatGptErrorModel.self, from: data)
                        completionBlock(nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, response.error)
            }
        }
    }
    
}
