//
//  AppViewModel.swift
//  SodaLive
//
//  Created by klaus on 3/6/25.
//

import Combine
import AdSupport
import AppTrackingTransparency

final class AppViewModel: ObservableObject {
    private var subscription = Set<AnyCancellable>()
    
    private let userRepository = UserRepository()
    
    func fetchAndUpdateIdfa() {
        AppState.shared.alreadyUpdatedMarketingInfo = true
        ATTrackingManager.requestTrackingAuthorization { [unowned self] status in
            if status == .authorized {
                if !UserDefaults.string(forKey: UserDefaultsKey.token).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                    let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                    let pid = UserDefaults.string(forKey: .marketingPid)
                    self.userRepository.updateMarketingInfo(request: MarketingInfoUpdateRequest(adid: idfa, pid: pid))
                        .sink { result in
                            switch result {
                            case .finished:
                                DEBUG_LOG("finish")
                            case .failure(let error):
                                ERROR_LOG(error.localizedDescription)
                            }
                        } receiveValue: { _ in
                        }
                        .store(in: &self.subscription)
                }
            } else {
                if !UserDefaults.string(forKey: UserDefaultsKey.token).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                    let pid = UserDefaults.string(forKey: .marketingPid)
                    self.userRepository.updateMarketingInfo(request: MarketingInfoUpdateRequest(adid: "", pid: pid))
                        .sink { result in
                            switch result {
                            case .finished:
                                DEBUG_LOG("finish")
                            case .failure(let error):
                                ERROR_LOG(error.localizedDescription)
                            }
                        } receiveValue: { _ in
                        }
                        .store(in: &self.subscription)
                }
            }
        }
    }
    
    func getMemberInfo() {
        if !UserDefaults.string(forKey: UserDefaultsKey.token).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            userRepository.getMemberInfo()
                .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(ApiResponse<GetMemberInfoResponse>.self, from: responseData)
                        
                        if let data = decoded.data, decoded.success {
                            UserDefaults.set(data.can, forKey: .can)
                            UserDefaults.set(data.isAuth, forKey: .auth)
                            UserDefaults.set(data.role.rawValue, forKey: .role)
                            UserDefaults.set(data.auditionNotice ?? false, forKey: .isAuditionNotification)
                            if data.followingChannelLiveNotice == nil && data.followingChannelUploadContentNotice == nil && data.messageNotice == nil {
                                AppState.shared.isShowNotificationSettingsDialog = true
                            }
                            
                            let dateFormatter = DateFormatter()
                            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                            
                            let currentDate = Date()
                            let lastActiveDate = dateFormatter.string(from: currentDate)
                            
                            var params = [
                                "nickname": UserDefaults.string(forKey: .nickname),
                                "last_active_date": lastActiveDate,
                                "charge_count": data.chargeCount,
                                "signup_date": data.signupDate,
                                "is_auth": data.isAuth,
                                "can": data.can
                            ]
                            
                            if data.isAuth {
                                params["gender"] = data.gender
                            }
                            
                            NotiflyClient.shared.setUser(userId: UserDefaults.int(forKey: .userId), params: params)
                        }
                    } catch {
                        print(error)
                    }
                }
                .store(in: &subscription)
        }
    }
}
