#include <spdlog/spdlog.h>
#include "./initialize_provider.hpp"
#include "../../protocol/transform/facade.hpp"

namespace lsp::providers::initialize
{
    std::string InitializeProvider::GetMethod() const
    {
        return "initialize";
    }

    std::string InitializeProvider::GetProviderName() const
    {
        return "InitializeProvider";
    }

    std::string InitializeProvider::ProvideResponse(const protocol::RequestMessage& request, ProviderContext& context)
    {
        spdlog::debug("InitializeProvider: Providing response for method {}", request.method);
        protocol::ResponseMessage response;
        response.id = request.id;
        response.result = transform::LSPAny(BuildInitializeResult());
        std::string json;
        auto ec = glz::write_json(response, json);
        if (ec)
        {
            context.TriggerLifecycleEvent(ServerLifecycleEvent::kInitializeFailed);
            return BuildErrorResponseMessage(request, protocol::ErrorCode::kInternalError, "Internal error");
        }
        context.TriggerLifecycleEvent(ServerLifecycleEvent::kInitialized);
        return json;
    }

    protocol::InitializeResult InitializeProvider::BuildInitializeResult()
    {
        protocol::InitializeResult result;
        result.serverInfo.name = "TSL Language Server";
        result.serverInfo.version = "1.0.0";
        protocol::TextDocumentSyncOptions opts;
        opts.openClose = true;
        opts.change = protocol::TextDocumentSyncKind::kIncremental;
        protocol::CompletionOptions completion_provider;
        completion_provider.resolveProvider = false;

        result.capabilities.textDocumentSync = opts;
        result.capabilities.completionProvider = completion_provider;
        return result;
    }

}
