#pragma once

#include <string>
#include <httplib.h>

#include "EnvConfig.h"
#include "TokenStore.h"

namespace CppModelBase
{
    class AuthHandler
    {
    private:
        EnvConfig config;
        TokenStore tokenStore;

        std::string token = "";
        std::string refreshToken = "";

        std::string authHost;
        std::string clientId;
        std::string clientSecret;

        httplib::Server loginServer;

        void GetLoginResult(const httplib::Request &req, httplib::Response &res);
        void AwaitServer();

        void OpenBrowser(const std::string &url);
        std::string StartLocalServer();

        std::string ExchangeAuthCodeForToken(const std::string &code);
        std::string RefreshAccessToken();
        std::string LoginWithPassword();

        void LoadTokens();
        void StoreTokens(const std::string &accessToken, const std::string &refreshToken);

        std::string GetAuthServerUrl();

    public:
        AuthHandler();
        ~AuthHandler();

        std::string GetApiKey();
        std::string Login();
        bool IsTokenExpired(const std::string &token);
        std::string GetFirstGroup(const std::string &token);
        void Relogin();

        static bool CanLoginNonInteractively();
        static void RequireNonInteractive(const std::string &testName);
    };
}
