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

namespace lsp::providers::shutdown
{
    std::string ShutdownProvider::GetMethod() const
    {
        return "shutdown";
    }

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

    std::string ShutdownProvider::ProvideResponse(const protocol::RequestMessage& request, ProviderContext& context)
    {
        spdlog::debug("ShutdownProvider: Providing response for method {}", request.method);

        try
        {
            // 触发关闭事件
            context.TriggerLifecycleEvent(ServerLifecycleEvent::kShuttingDown);

            // 构建响应 - shutdown 返回 null
            protocol::ResponseMessage response;
            response.id = request.id;

            std::string json;
            auto ec = glz::write_json(response, json);
            if (ec)
            {
                return BuildErrorResponseMessage(request, protocol::ErrorCode::kInternalError, "Failed to serialize response");
            }

            spdlog::info("Shutdown request processed successfully");
            return json;
        }
        catch (const std::exception& e)
        {
            spdlog::error("Shutdown request failed: {}", e.what());
            return BuildErrorResponseMessage(request, protocol::ErrorCode::kInternalError, e.what());
        }
    }

}
