/*******************************************************************************
 * Copyright (c) 2025, 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 <string>
#include <memory>
#include <vector>
#include <mutex>
#include <deque>
#include <unordered_map>
#include <chrono>
#include <uuidp.h>

#ifndef Windows
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

#include "session.h"
#include "user.h"
#include "exception.h"

#include <httppp/http.h>

#pragma once

#ifdef Windows
#define VISIBILITY __declspec(dllexport)
#else
#define VISIBILITY __attribute__((visibility("default")))
#endif


namespace authdb {   
    namespace client {
        class VISIBILITY ClientConnection {
        public:
            ClientConnection();
            ~ClientConnection();

            void setUrl(const libhttppp::HttpUrl& url);
            void setUrl(const std::string &url);
            void setClientName(const std::string &name);
            void setClientSecret(const std::string &secret);
            void setUsername(const std::string &username);
            void setUserPassword(const std::string &password);
            void setMaxTries(int maxtries);
            void setTimeout(int timeout_sec);

            const uuid::uuid &getClientId();
            const uuid::uuid &getSessionID();

            void setSessionID(const uuid::uuid &sid);

             void reConnect();
        private:
            libhttppp::HttpUrl _Url;
            std::string _CltName;
            std::string _CltSecret;
            std::string _UserName;
            std::string _UserPassword;
            std::string _RequestPath;

            std::unique_ptr<libhttppp::HttpClient> _Client;
            uuid::uuid             _SessionID;
            uuid::uuid             _ClientId;
            int                    _MaxTries = 3;
            int                    _Timeout = 10;
            friend inline void ensure_http_client(ClientConnection& con);
            friend std::vector<char> post_with_redirect(ClientConnection& con,
                                                        libhttppp::HttpRequest& req,
                                                        const std::vector<char>& out);
            friend class Client;
        };

        class VISIBILITY Client {
        public:
            Client(ClientConnection &clt);
            ~Client();

            bool UserAuth();
            bool ClientAuth();

            std::string addConnection(const std::string &clientname,const std::string &cltsecret);
            void remConnection(const uuid::uuid &clientid);
            void editConnection(const uuid::uuid& clientid,const std::string &clientname,const std::string &cltsecret);

            void SessionInfo(class SessionData &sdat);
            bool remSession();

            bool GPOcheck(class ::uuid::uuid gpoid);
            bool GPOexits(class ::uuid::uuid gpoid);
            std::string GPOadd(const uuid::uuid &gpoid,const std::string &name,const std::string &desc,bool gpodefault,const std::vector<std::string> &members);

            void UserInfo(class UserData &udat);
            void changeUserPw(const std::string& oldpw,const std::string& newpw);

            void getAvatar(const ::uuid::uuid &did,const ::uuid::uuid &uid,libhttppp::HttpRequest &resq, libhttppp::HttpResponse &resp);

            struct GroupInfo {
                std::string gid;
                std::string name;
            };

            std::vector<GroupInfo> listGroups();

            // GPO result cache TTL in seconds (default 300 = 5 min)
            static void setGpoCacheTTL(int seconds);
        private:
            ClientConnection &_Con;

            // Shared GPO result cache: "session_id:gpo_id" -> expiry
            static constexpr int DEFAULT_GPO_CACHE_TTL = 300;
            static int _GpoCacheTTL;
            static std::mutex _GpoCacheMutex;
            static std::unordered_map<std::string,
                std::chrono::steady_clock::time_point> _GpoCache;
            static bool checkGpoCache(const std::string& key);
            static void cacheGpoResult(const std::string& key);

            friend class Session;
        };

        // ---- ConnectionPool: reuses TCP connections to authdb ----

        class ConnectionPool;

        class VISIBILITY PooledConnection {
        public:
            PooledConnection(PooledConnection&& other) noexcept;
            PooledConnection& operator=(PooledConnection&& other) noexcept;
            ~PooledConnection();

            PooledConnection(const PooledConnection&) = delete;
            PooledConnection& operator=(const PooledConnection&) = delete;

            // Access the underlying connection and client
            ClientConnection& connection();
            Client& client();

            // Set per-request session ID
            void setSessionID(const uuid::uuid& sid);

        private:
            friend class ConnectionPool;
            PooledConnection(ConnectionPool* pool,
                             std::unique_ptr<ClientConnection> con,
                             std::unique_ptr<Client> clt);

            ConnectionPool* _Pool;
            std::unique_ptr<ClientConnection> _Con;
            std::unique_ptr<Client> _Clt;
        };

        class VISIBILITY ConnectionPool {
        public:
            ConnectionPool(const std::string& url,
                           const std::string& client_name,
                           const std::string& client_secret,
                           std::size_t max_idle = 4);
            ~ConnectionPool();

            ConnectionPool(const ConnectionPool&) = delete;
            ConnectionPool& operator=(const ConnectionPool&) = delete;

            // Acquire a ready-to-use connection (creates new if pool empty)
            PooledConnection acquire();

        private:
            friend class PooledConnection;
            void release(std::unique_ptr<ClientConnection> con,
                         std::unique_ptr<Client> clt);

            std::string _Url;
            std::string _CltName;
            std::string _CltSecret;
            std::size_t _MaxIdle;
            std::mutex  _Mutex;

            struct IdleEntry {
                std::unique_ptr<ClientConnection> con;
                std::unique_ptr<Client> clt;
            };
            std::deque<IdleEntry> _Idle;
        };
    };
};
