//
//  AuditionViewModel.swift
//  SodaLive
//
//  Created by klaus on 1/5/25.
//

import Foundation
import Combine

final class AuditionViewModel: ObservableObject {
    
    private let repository = AuditionRepository()
    private let userRepository = UserRepository()
    private var subscription = Set<AnyCancellable>()
    
    @Published var errorMessage = ""
    @Published var isShowPopup = false
    @Published var isLoading = false
    
    @Published var auditionList = [GetAuditionListItem]()
    @Published var inProgressCount = 0
    @Published var completedCount = 0
    
    @Published var firstIsOffIndex = -1
    
    var page = 1
    var isLast = false
    private let pageSize = 10
    
    func getAuditionList() {
        if !isLast && !isLoading {
            isLoading = true
            
            repository.getAuditionList(page: page, size: pageSize)
                .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<GetAuditionListResponse>.self, from: responseData)
                        
                        if let data = decoded.data, decoded.success {
                            if page == 1 {
                                self.auditionList.removeAll()
                            }
                            
                            self.inProgressCount = data.inProgressCount
                            self.completedCount = data.completedCount
                            
                            if !data.items.isEmpty {
                                page += 1
                                self.auditionList.append(contentsOf: data.items)
                                self.firstIsOffIndex = self.auditionList.firstIndex(where: { $0.isOff }) ?? -1
                            } else {
                                isLast = true
                            }
                        } else {
                            if let message = decoded.message {
                                self.errorMessage = message
                            } else {
                                self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
                            }
                            
                            self.isShowPopup = true
                        }
                    } catch {
                        self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
                        self.isShowPopup = true
                    }
                    
                    self.isLoading = false
                }
                .store(in: &subscription)
        }
    }
    
    func updateNotificationSettings() {
        let isAuditionNotification = UserDefaults.bool(forKey: .isAuditionNotification)
        
        userRepository.updateNotificationSettings(audition: !isAuditionNotification)
            .sink { result in
                switch result {
                case .finished:
                    DEBUG_LOG("finish")
                case .failure(let error):
                    ERROR_LOG(error.localizedDescription)
                }
            } receiveValue: { response in
                let responseData = response.data
                
                do {
                    let jsonDecoder = JSONDecoder()
                    let decoded = try jsonDecoder.decode(ApiResponseWithoutData.self, from: responseData)
                    
                    if decoded.success {
                        UserDefaults.set(!isAuditionNotification, forKey: .isAuditionNotification)
                    }
                } catch {}
            }
            .store(in: &subscription)
    }
}
