import Foundation
import Combine

final class ResolverMiddleware {
    func middleware(state: ClientState, action: ClientAction) -> AnyPublisher<ClientAction, Never> {
        switch action {
        case .connectionAction(.reconnect):
            return Future<ClientAction, Never> { promise in
                Task {
                    do {
                        let records = try await SRVResolver.resolve(domain: state.jid.domainPart)
                        promise(.success(.connectionAction(.srvRecordsUpdated(records))))
                    } catch {
                        promise(.success(.clientError(error as? ClientError ?? .generalError)))
                    }
                }
            }
                .eraseToAnyPublisher()

        default:
            return Empty().eraseToAnyPublisher()
        }
    }
}
