////
////  refreshtokenex.swift
////  volnahub (iOS)
////
////  Created by cheykrym on 11/06/2025.
////
//
//import Foundation
//
//func autoLogin(completion: @escaping (Bool, String?) -> Void) {
//    guard let username = UserDefaults.standard.string(forKey: "currentUser") else {
//        completion(false, "Не найден текущий пользователь")
//        return
//    }
//    
//    guard let accessToken = KeychainService.shared.get(forKey: "access_token", service: username),
//          let refreshToken = KeychainService.shared.get(forKey: "refresh_token", service: username) else {
//        completion(false, "Токены отсутствуют. Пожалуйста, войдите снова.")
//        return
//    }
//    
////        let url = URL(string: "\(AppConfig.API_SERVER)/auth/refresh")!
////        var request = URLRequest(url: url)
////        request.httpMethod = "POST"
////        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
//////        request.setValue("VolnahubApp", forHTTPHeaderField: "User-Agent")
////        request.setValue("VolnahubApp", forHTTPHeaderField: "\(AppConfig.USER_AGENT)")
////
////        let payload: [String: String] = [
////            "access_token": accessToken,
////            "refresh_token": refreshToken
////        ]
////
////        do {
////            let jsonData = try JSONEncoder().encode(payload)
////            request.httpBody = jsonData
////        } catch {
////            DispatchQueue.main.async {
////                completion(false, "Не удалось подготовить запрос.")
////            }
////            return
////        }
////
////        let task = URLSession.shared.dataTask(with: request) { data, response, error in
////            DispatchQueue.main.async {
////                if let error = error {
////                    print("AutoLogin error: \(error.localizedDescription)")
////                    completion(false, "Ошибка сети: \(error.localizedDescription)")
////                    return
////                }
////
////                guard let httpResponse = response as? HTTPURLResponse else {
////                    completion(false, "Некорректный ответ от сервера.")
////                    return
////                }
////
////                guard (200...299).contains(httpResponse.statusCode) else {
////                    if httpResponse.statusCode == 401 {
////                        print("деавторизация") //TODO
////                        completion(false, "Сессия недействительна. Пожалуйста, войдите снова.")
////                    } else if httpResponse.statusCode == 502 {
////                        completion(false, "Сервер не отвечает. Попробуйте позже.")
////                    } else {
////                        completion(false, "Ошибка сервера: \(httpResponse.statusCode)")
////                    }
////                    return
////                }
////
////                guard let data = data else {
////                    completion(false, "Пустой ответ от сервера.")
////                    return
////                }
////
////                do {
////                    let decoder = JSONDecoder()
////                    let refreshResponse = try decoder.decode(TokenRefreshResponse.self, from: data)
////
////                    KeychainService.shared.save(refreshResponse.access_token, forKey: "access_token", service: username)
////
////                    print("AutoLogin: токен обновлён.")
////                    completion(true, nil)
////                } catch {
////                    print("AutoLogin decode error: \(error.localizedDescription)")
////                    completion(false, "Ошибка обработки ответа сервера.")
////                }
////            }
////        }
////        task.resume()
//}
