/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "socket.h"
#include "exception.h"
#include "error.h"
#include "eventapi.h"

#include <cstdio>
#include <cstring>
#include <cerrno>
#include <iostream>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/un.h>
#include <netinet/tcp.h>

#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif

namespace netplus {

tcp::tcp() : socket() {
    _Socket = -1;
    _Type   = sockettype::TCP;
}

tcp::tcp(SOCKET sock) : socket() {
    _Socket = sock;
    _Type   = sockettype::TCP;
}

tcp::~tcp() {
    if (_Socket >= 0)
        socket::close();
}

tcp::tcp(const std::string& uxsocket, int maxconnections, int sockopts)
: socket() {
    _Maxconnections = maxconnections;
    _Type = sockettype::TCP;

    if ((_Socket = ::socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        NetException e;
        e[NetException::Critical] << "Can't create Unix TCP Socket";
        throw e;
    }

    sockaddr_un un{};
    un.sun_family = AF_UNIX;
    std::snprintf(un.sun_path, sizeof(un.sun_path), "%s", uxsocket.c_str());

    std::memset(&_Addr, 0, sizeof(_Addr));
    std::memcpy(&_Addr, &un, sizeof(un));
    _AddrLen = sizeof(un);

    int opt = 1;
    if (sockopts == -1) sockopts = SO_REUSEADDR;

    if (sockopts & SO_REUSEADDR) {
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }
#ifdef SO_REUSEPORT
    if (sockopts & SO_REUSEPORT) {
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
    }
#endif
}

tcp::tcp(const std::string& addr, int port, int maxconnections, int sockopts)
: socket() {
    NetException exception;
    _Maxconnections = maxconnections;
    _Type = sockettype::TCP;

    if (sockopts == -1)
        sockopts = SO_REUSEADDR;

    addrinfo hints{};
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags    = AI_PASSIVE;

    addrinfo* result = nullptr;

    char serv[32];
    std::snprintf(serv, sizeof(serv), "%d", port);

    int gai = ::getaddrinfo(addr.empty() ? nullptr : addr.c_str(), serv, &hints, &result);
    if (gai != 0) {
        exception[NetException::Critical] << "getaddrinfo: " << gai_strerror(gai);
        throw exception;
    }

    for (addrinfo* rp = result; rp; rp = rp->ai_next) {
        _Socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if (_Socket < 0)
            continue;

        // ✅ store sockaddr into sockaddr_storage
        setAddrFromAI(rp);
        break;
    }

    ::freeaddrinfo(result);

    if (_Socket < 0) {
        exception[NetException::Critical] << "Failed to create TCP socket";
        throw exception;
    }

    int opt = 1;
    if (sockopts & SO_REUSEADDR) {
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }
#ifdef SO_REUSEPORT
    if (sockopts & SO_REUSEPORT) {
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
    }
#endif

    // For an IPv6 listening socket, disable IPV6_V6ONLY so the socket accepts
    // both IPv6 and IPv4-mapped connections (dual-stack). This makes binding to
    // "::" serve IPv4 clients too, regardless of the system bindv6only sysctl.
    if (reinterpret_cast<sockaddr*>(&_Addr)->sa_family == AF_INET6) {
        int v6only = 0;
        ::setsockopt(_Socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only));
    }
}

void tcp::bind() {
    if (_Bound) return;
    if (::bind(_Socket, reinterpret_cast<sockaddr*>(&_Addr), _AddrLen) < 0) {
        NetException e;
        e[NetException::Error] << "tcp::bind failed: " << strerror(errno);
        throw e;
    }
    _Bound = true;
}

void tcp::listen() {
    if (_Listening) return;
    if (::listen(_Socket, _Maxconnections) < 0) {
        NetException e;
        e[NetException::Critical] << "tcp::listen failed: " << strerror(errno);
        throw e;
    }
    _Listening = true;
}

void tcp::setNonBlock() {
    setFlag(O_NONBLOCK, 1);
}

void tcp::setBlock() {
    setFlag(O_NONBLOCK, 0);
}

int tcp::getMaxconnections() {
    return _Maxconnections;
}

tcp& tcp::operator=(SOCKET sock) {
    _Socket = sock;
    return *this;
}

void tcp::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    sockaddr_storage peer{};
    socklen_t peerLen = sizeof(peer);

    SOCKET cfd = -1;
#if defined(SOCK_NONBLOCK)
    // Fast path where accept4 is available.
    int flags = nonblock ? SOCK_NONBLOCK : 0;
    cfd = ::accept4(_Socket, reinterpret_cast<sockaddr*>(&peer), &peerLen, flags);
#else
    cfd = ::accept(_Socket, reinterpret_cast<sockaddr*>(&peer), &peerLen);
#endif
    if (cfd < 0) {
        NetException e;
        int et = (errno == EAGAIN || errno == EWOULDBLOCK) ? NetException::Note : NetException::Error;
        e[et] << "tcp::accept failed: " << strerror(errno);
        throw e;
    }

#if !defined(SOCK_NONBLOCK)
    if (nonblock) {
        int sockFlags = ::fcntl(cfd, F_GETFL, 0);
        if (sockFlags < 0 || ::fcntl(cfd, F_SETFL, sockFlags | O_NONBLOCK) < 0) {
            int saved = errno;
            ::close(cfd);
            NetException e;
            e[NetException::Error] << "tcp::accept set non-blocking failed: " << strerror(saved);
            throw e;
        }
    }
#endif

    *csock = cfd;
    csock->_Addr = peer;
    csock->_AddrLen = peerLen;

    // Disable Nagle's algorithm — reduces latency for small HTTP frames
    int one = 1;
    ::setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
}

size_t tcp::sendData(buffer& data, int flags) {
    const char* p = data.ptr ? data.data.ptr : data.data.buf;
    ssize_t s = ::send(_Socket, p, data.size, flags | MSG_NOSIGNAL);
    if (s < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            NetException e;
            e[NetException::Note] << "tcp::sendData would block";
            throw e;
        }
        NetException e;
        e[NetException::Error] << "tcp::sendData failed: " << strerror(errno);
        throw e;
    }
    return (size_t)s;
}

size_t tcp::recvData(buffer& data, int flags) {
    ssize_t r = ::recv(_Socket, data.data.buf, data.size, flags);
    if (r > 0) {
        data.size = (size_t)r;
        return (size_t)r;
    }

    if (r == 0) {
        NetException e;
        e[NetException::Error] << "tcp::recvData peer closed (EOF)";
        throw e;
    }

    if (errno == EAGAIN || errno == EWOULDBLOCK) {
        NetException e;
        e[NetException::Note] << "tcp::recvData would block";
        throw e;
    }

    NetException e;
    e[NetException::Error] << "tcp::recvData failed: " << strerror(errno);
    throw e;
}

void netplus::tcp::connect(const std::string& addr, int port, bool nonblock)
{
    NetException exception;

    addrinfo hints{};
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    addrinfo* result = nullptr;

    char serv[32];
    std::snprintf(serv, sizeof(serv), "%d", port);

    int gai = ::getaddrinfo(addr.c_str(), serv, &hints, &result);
    if (gai != 0) {
        exception[NetException::Error]
            << "tcp::connect: getaddrinfo failed: " << gai_strerror(gai);
        throw exception;
    }

    for (addrinfo* rp = result; rp; rp = rp->ai_next) {

        // -------------------------------------------------------
        // 1) ensure socket exists and matches family
        // -------------------------------------------------------
        if (_Socket >= 0) {
            // if family mismatch, close and recreate
            sockaddr_storage tmp{};
            socklen_t tmpLen = sizeof(tmp);
            if (::getsockname(_Socket, (sockaddr*)&tmp, &tmpLen) == 0) {
                if (tmp.ss_family != rp->ai_family) {
                    ::close(_Socket);
                    _Socket = -1;
                }
            }
        }

        if (_Socket < 0) {
            _Socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
            if (_Socket < 0)
                continue;
        }

        // -------------------------------------------------------
        // 2) set nonblock BEFORE connect() if requested
        // -------------------------------------------------------
        if (nonblock) {
            try {
                setNonBlock();
            } catch (...) {
                ::close(_Socket);
                _Socket = -1;
                continue;
            }
        }

        // -------------------------------------------------------
        // 3) connect()
        // -------------------------------------------------------
        if (::connect(_Socket, rp->ai_addr, rp->ai_addrlen) == 0) {
            // ✅ connected immediately
            setAddrFromAI(rp);

            // Disable Nagle's algorithm for low-latency HTTP
            int one = 1;
            ::setsockopt(_Socket, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));

            ::freeaddrinfo(result);
            return;
        }

        // -------------------------------------------------------
        // 4) nonblocking in progress
        // -------------------------------------------------------
        if (nonblock && (errno == EINPROGRESS || errno == EWOULDBLOCK)) {
            setAddrFromAI(rp);

            ::freeaddrinfo(result);

            NetException n;
            n[NetException::Note] << "tcp::connect: EINPROGRESS";
            throw n; // caller waits EPOLLOUT/select
        }

        // -------------------------------------------------------
        // 5) fatal error -> try next addrinfo
        // -------------------------------------------------------
        ::close(_Socket);
        _Socket = -1;
    }

    ::freeaddrinfo(result);

    exception[NetException::Error]
        << "tcp::connect: could not connect to "
        << addr << ":" << port
        << " (" << strerror(errno) << ")";
    throw exception;
}

void tcp::connectTimeout(const std::string& addr, int port, int timeout_ms) {
    try {
        connect(addr, port, true);
        return; // connected immediately
    } catch (NetException &e) {
        if (e.getErrorType() != NetException::Note)
            throw;
    }

    netplus::socketwait sw;
    if (!sw.waitWrite(*this, timeout_ms)) {
        NetException ne;
        ne[NetException::Error] << "tcp::connectTimeout: timed out connecting to "
                                 << addr << ":" << port;
        throw ne;
    }

    int err = 0;
    socklen_t errlen = sizeof(err);
    if (::getsockopt(fd(), SOL_SOCKET, SO_ERROR, &err, &errlen) != 0 || err != 0) {
        NetException ne;
        ne[NetException::Error] << "tcp::connectTimeout: could not connect to "
                                 << addr << ":" << port << " (" << strerror(err) << ")";
        throw ne;
    }
}

void tcp::getAddress(std::string& addr) {
    char buf[INET6_ADDRSTRLEN]{};

    sockaddr* sa = reinterpret_cast<sockaddr*>(&_Addr);

    if (sa->sa_family == AF_INET) {
        inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(sa)->sin_addr, buf, sizeof(buf));
        addr = buf;
    } else if (sa->sa_family == AF_INET6) {
        inet_ntop(AF_INET6, &reinterpret_cast<sockaddr_in6*>(sa)->sin6_addr, buf, sizeof(buf));
        addr = buf;
    } else {
        addr = "";
    }
}

void tcp::flush_out() {
}

} // namespace netplus
