#include "include/cvsock.h"

#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/vsock.h>
#include <unistd.h>

int nucleic_vsock_listen(uint32_t port, int backlog) {
    int fd = socket(AF_VSOCK, SOCK_STREAM, 0);
    if (fd < 0) return -errno;

    struct sockaddr_vm addr;
    memset(&addr, 0, sizeof(addr));
    addr.svm_len = sizeof(addr);  // macOS-specific BSD length field (Linux has none)
    addr.svm_family = AF_VSOCK;
    addr.svm_cid = VMADDR_CID_ANY;
    addr.svm_port = port;

    if (bind(fd, (const struct sockaddr *)&addr, sizeof(addr)) != 0) {
        int e = errno;
        close(fd);
        return -e;
    }
    if (listen(fd, backlog) != 0) {
        int e = errno;
        close(fd);
        return -e;
    }
    return fd;
}
