//
//  API.swift
//  JJUNGTABLE
//
//  Created by Sean Kim on 6/5/24.
//

import SwiftUI
import Combine

struct InfoKey {
    static var httpURL: String {
        return Bundle.main.object(forInfoDictionaryKey: "httpURL") as? String ?? ""
    }
    
    static var httpsURL: String {
        return Bundle.main.object(forInfoDictionaryKey: "httpsURL") as? String ?? ""
    }
    
    static var apiPort: String {
        return Bundle.main.object(forInfoDictionaryKey: "PORT") as? String ?? ""
    }
}

class API {
    static let shared = API()
    
    private init() {}
    
    private func makeURLComponents(path: String, queryItems: [URLQueryItem]? = nil) -> Result<URLComponents, Error> {
//        let url = InfoKey.httpURL
//        let port = InfoKey.apiPort
        let url = "https://ipstein.myds.me"
        let port = "5004"
        let path = "/JJ\(path)"
        
        printLog("\(url):\(port)\(path)?\(queryItems)")
        
        if url == "" || port == "" {
            return .failure(API_ERROR(caseType: .API_PLIST_WRONG, message: "저장된 API 주소 오류"))
        }
        
        guard var components = URLComponents(string: url) else {
            return .failure(API_ERROR(caseType: .API_PATH_WRONG, message: "API 주소 오류"))
        }
        components.port = Int(port)
        components.path = path
        components.queryItems = queryItems
        
        return .success(components)
    }
    
    func createUserInfo() -> AnyPublisher<[UserInfo], Error> {
//        switch self.makeURLComponents() {
//        case .success(let components):
//            break
//        case .failure(let error):
//            return Fail(error: error)
//                .eraseToAnyPublisher()
//        }
        
        return Fail(error: API_ERROR(caseType: .API_PATH_WRONG, message: "API 주소 오류"))
            .eraseToAnyPublisher()
    }
    
    func readData(path: String, queryItems: [URLQueryItem]? = nil) -> AnyPublisher<Data, Error> {
        switch self.makeURLComponents(path: path, queryItems: queryItems) {
        case .success(let components):
            guard let url = components.url else {
                return Fail(error: API_ERROR(caseType: .API_PATH_WRONG, message: "API 주소 오류"))
                    .eraseToAnyPublisher()
            }
            return URLSession.shared.dataTaskPublisher(for: url)
                .tryMap { result in
                    guard let httpResponse = result.response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                        throw API_ERROR(caseType: .API_CONNECT, message: "서버 접속 오류")
                    }
                    return result.data
                }
                .mapError { error in
                    return API_ERROR(caseType: .API_READ, message: "\(error.localizedDescription)")
                }
                .receive(on: DispatchQueue.main)
                .eraseToAnyPublisher()
            
        case .failure(let error):
            return Fail(error: error)
                .eraseToAnyPublisher()
        }
        
    }
    
}
