local lsp = require("ferris.private.ra_lsp")
local error = require("ferris.private.error")
local config = require("ferris.private.config")

---Opens the Cargo.toml file of a project.
local function open_documentation()
    if not error.ensure_ra() then return end

    lsp.experimental_request(
        "externalDocs",
        vim.lsp.util.make_position_params(0, lsp.offset_encoding()),
        function(response)
            if response.result == nil then
                if response.error == nil then
                    error.raise("no answer from rust-analyzer for external documentation")
                    return
                end

                error.raise_lsp_error("error opening external documentation", response.error)
                return
            end

            local url = response.result
            if url["web"] then
                local path = url["local"] and string.sub(url["local"], 7)
                if path and vim.uv.fs_stat(path) then
                    url = url["local"]
                else
                    url = url["web"]
                end
            end

            if type(config.opts.url_handler) ~= "string" then
                config.opts.url_handler(url)
                return
            end

            vim.system({ config.opts.url_handler, url }, { detach = true })
        end
    )
end

return open_documentation
