const std = @import("std");

pub fn resolveHostAddress(allocator: std.mem.Allocator, host: []const u8, port: u16) !std.net.Address {
    return std.net.Address.parseIp(host, port) catch |err| switch (err) {
        error.InvalidIPAddressFormat => resolveHostname(allocator, host, port),
        else => return err,
    };
}

fn resolveHostname(allocator: std.mem.Allocator, host: []const u8, port: u16) !std.net.Address {
    var address_list = try std.net.getAddressList(allocator, host, port);
    defer address_list.deinit();

    if (address_list.addrs.len == 0) return error.HostResolutionFailed;

    return address_list.addrs[0];
}

test "resolve hostnames for WebSocket connections" {
    _ = try resolveHostAddress(std.testing.allocator, "localhost", 9100);
}
