//
//  AuditionDetailViewModel.swift
//  SodaLive
//
//  Created by klaus on 1/6/25.
//

import Foundation
import Combine

final class AuditionDetailViewModel: ObservableObject {
    
    private let repository = AuditionRepository()
    private var subscription = Set<AnyCancellable>()
    
    @Published var errorMessage = ""
    @Published var isShowPopup = false
    @Published var isLoading = false
    
    @Published var response: GetAuditionDetailResponse? = nil
    @Published var title: String = "보이스온"
    
    func getAuditionDetail(auditionId: Int, onFailure: @escaping () -> Void) {
        isLoading = true
        
        repository.getAuditionDetail(auditionId: auditionId)
            .sink { result in
                switch result {
                case .finished:
                    DEBUG_LOG("finish")
                case .failure(let error):
                    ERROR_LOG(error.localizedDescription)
                }
            } receiveValue: { [unowned self] response in
                let responseData = response.data
                
                do {
                    let jsonDecoder = JSONDecoder()
                    let decoded = try jsonDecoder.decode(ApiResponse<GetAuditionDetailResponse>.self, from: responseData)
                    
                    if let data = decoded.data, decoded.success {
                        self.response = data
                        self.title = data.title
                    } else {
                        if let message = decoded.message {
                            self.errorMessage = message
                        } else {
                            self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
                        }
                        
                        self.isShowPopup = true
                        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                            onFailure()
                        }
                    }
                } catch {
                    self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
                    self.isShowPopup = true
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                        onFailure()
                    }
                }
                
                self.isLoading = false
            }
            .store(in: &subscription)
    }
}
