//
//  SignUpViewModel.swift
//  SodaLive
//
//  Created by klaus on 2023/08/09.
//

import UIKit
import Combine

import Moya

final class SignUpViewModel: ObservableObject {
    private let appViewModel = AppViewModel()
    private let repository = UserRepository()
    private var subscription = Set<AnyCancellable>()
    
    @Published var errorMessage = ""
    @Published var isShowPopup = false
    @Published var isLoading = false
    
    @Published var email = ""
    @Published var password = ""
    
    @Published var isAgreeTerms = false
    @Published var isAgreePrivacyPolicy = false
    
    func signUp() {
        if validate() {
            isLoading = true
            
            let request = SignUpRequest(
                email: email,
                password: password,
                pushToken: UserDefaults.string(forKey: .pushToken),
                marketingPid: UserDefaults.string(forKey: .marketingPid),
                isAgreeTermsOfService: true,
                isAgreePrivacyPolicy: true
            )
            
            repository.signUp(request: request)
                .sink { result in
                    switch result {
                    case .finished:
                        DEBUG_LOG("finish")
                    case .failure(let error):
                        ERROR_LOG(error.localizedDescription)
                    }
                } receiveValue: { response in
                    self.isLoading = false
                    let responseData = response.data
                    do {
                        let jsonDecoder = JSONDecoder()
                        let decoded = try jsonDecoder.decode(ApiResponse<LoginResponse>.self, from: responseData)
                        
                        if let data = decoded.data, decoded.success {
                            FirebaseTracking.shared.signUp(method: "email")
                            UserDefaults.set(data.profileImage, forKey: .profileImage)
                            UserDefaults.set(data.nickname, forKey: .nickname)
                            UserDefaults.set(data.userId, forKey: .userId)
                            UserDefaults.set(data.email, forKey: .email)
                            UserDefaults.set(data.token, forKey: .token)
                            self.appViewModel.fetchAndUpdateIdfa()
                            AppState.shared.isChangeAdultContentVisible = true
                            AppState.shared.setAppStep(step: .splash)
                        } else {
                            if let message = decoded.message {
                                self.errorMessage = message
                            } else {
                                self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
                            }
                            
                            self.isShowPopup = true
                        }
                    } catch {
                        self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
                        self.isShowPopup = true
                    }
                }
                .store(in: &subscription)
        }
    }
    
    private func validate() -> Bool {
        if email.trimmingCharacters(in: .whitespaces).isEmpty || !validateEmail() {
            errorMessage = "올바른 이메일을 입력하세요"
            isShowPopup = true
            return false
        }
        
        if password.trimmingCharacters(in: .whitespaces).isEmpty {
            errorMessage = "비밀번호를 입력하세요"
            isShowPopup = true
            return false
        }
        
        if !validatePassword() {
            errorMessage = "영문, 숫자 포함 8자 이상의 비밀번호를 입력해 주세요."
            isShowPopup = true
            return false
        }
        
        if !isAgreeTerms || !isAgreePrivacyPolicy {
            errorMessage = "약관에 동의하셔야 회원가입이 가능합니다."
            isShowPopup = true
            return false
        }
        
        return true
    }
    
    private func validateEmail() -> Bool {
        let emailRegEx = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$"
        
        let predicate = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return predicate.evaluate(with: email)
    }
    
    private func validatePassword() -> Bool {
        let passwordRegEx = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d$@!%*#?&]{8,}$"
        
        let predicate = NSPredicate(format:"SELF MATCHES %@", passwordRegEx)
        return predicate.evaluate(with: password)
    }
}
