import SwiftUI
import Combine

class SearchViewModel: ObservableObject {
    @Published var searchText = ""
    @Published var users = [User]()
    
    private var cancellables = Set<AnyCancellable>()
    
    init() {
        $searchText
            .debounce(for: .milliseconds(500), scheduler: RunLoop.main)
            .removeDuplicates()
            .flatMap { query -> AnyPublisher<[User], Error> in
                if query.isEmpty {
                    return Just([])
                        .setFailureType(to: Error.self)
                        .eraseToAnyPublisher()
                } else {
                    return self.searchUsers(query: query)
                        .eraseToAnyPublisher()
                }
            }
            .catch { _ in Just([]) } // При ошибке возвращаем пустой массив
            .receive(on: RunLoop.main)
            .assign(to: \.users, on: self)
            .store(in: &cancellables)
    }
    
    func searchUsers(query: String) -> Future<[User], Error> {
        Future { promise in
            // Имитация сетевого запроса
            let mockUsers = [
                User(id: "1", username: "testuser1", email: "test1@test.com"),
                User(id: "2", username: "testuser2", email: "test2@test.com"),
                User(id: "3", username: query, email: "test3@test.com")
            ]
            promise(.success(mockUsers))
        }
    }
}