//
//  LoginViewModel.swift
//  VolnahubApp
//
//  Created by cheykrym on 09/06/2025.
//

import Foundation
import Combine

class LoginViewModel: ObservableObject {
    @Published var username: String = ""
    @Published var password: String = ""
    @Published var isLoading: Bool = true    // сразу true, чтобы показать спиннер при автологине
    @Published var showError: Bool = false
    @Published var errorMessage: String = ""
    @Published var isLoggedIn: Bool = false

    private let authService = AuthService()

    init() {
        // Если username сохранён, подставим его сразу
        if let savedUsername = UserDefaults.standard.string(forKey: "currentUser") {
            username = savedUsername
        }
        
        // Запускаем автологин
        autoLogin()
    }

    func autoLogin() {
        authService.autoLogin { [weak self] success, error in
            DispatchQueue.main.async {
//                self?.isLoading = false
                if success {
                    self?.isLoggedIn = true
                } else {
                    self?.isLoggedIn = false
                    self?.errorMessage = error ?? "Произошла ошибка."
                    self?.showError = false
                }
                self?.isLoading = false
            }
        }
    }


    func login() {
        isLoading = true
        showError = false
        
        authService.login(username: username, password: password) { [weak self] success, error in
            DispatchQueue.main.async {
                self?.isLoading = false
                if success {
                    self?.isLoggedIn = true
                } else {
                    self?.errorMessage = error ?? "Неизвестная ошибка"
                    self?.showError = true
                }
            }
        }
    }
    
    func registerUser(username: String, password: String, invite: String?, completion: @escaping (Bool, String?) -> Void) {
        authService.register(username: username, password: password, invite: invite) { [weak self] success, message in
            DispatchQueue.main.async {
                if success {
                    self?.isLoggedIn = true // 👈 переключаем на главный экран после автологина
                }
                completion(success, message)
            }
        }
    }

    func logoutCurrentUser() {
        authService.logoutCurrentUser { [weak self] success, error in
            DispatchQueue.main.async {
                if success {
                    self?.username = UserDefaults.standard.string(forKey: "currentUser") ?? ""
                    self?.password = ""
                    self?.isLoggedIn = true
                    self?.showError = false
                } else {
                    self?.username = ""
                    self?.password = ""
                    self?.isLoggedIn = false
                    self?.errorMessage = error ?? "Ошибка при деавторизации."
                    self?.showError = false
                }
            }
        }
    }

    
//    func logout() {
//        username = ""
//        password = ""
//        isLoggedIn = false
//        showError = false
//        errorMessage = ""
//    }
}
