local lspconfig = require("lspconfig")
local capabilities = require("cmp_nvim_lsp").default_capabilities(vim.lsp.protocol.make_client_capabilities())

-- Java binary (ensure it's Java 21)
local java_bin = "/usr/lib/jvm/java-21-openjdk/bin/java"

-- Find JDTLS and Lombok paths dynamically
local jdtls_path = "/home/prabhat/.local/share/nvim/mason/packages/jdtls"
local jdtls_launcher_jar = vim.fn.glob(jdtls_path .. "/plugins/org.eclipse.equinox.launcher_*.jar")
local lombok_jar = vim.fn.glob(jdtls_path .. "/lombok.jar")

lspconfig.jdtls.setup({
    cmd = {
        java_bin,
        "-Declipse.application=org.eclipse.jdt.ls.core.id1",
        "-Dosgi.bundles.defaultStartLevel=4",
        "-Declipse.product=org.eclipse.jdt.ls.core.product",
        "-Dlog.protocol=true",
        "-Dlog.level=INFO",
        "-Xmx2G",   -- Max heap size
        "-Xms256m", -- Min heap size
        "--add-modules=ALL-SYSTEM",
        "--add-opens", "java.base/java.util=ALL-UNNAMED",
        "--add-opens", "java.base/java.lang=ALL-UNNAMED",
        "-javaagent:" .. lombok_jar, -- Lombok support
        "-jar", jdtls_launcher_jar,  -- JDTLS launcher
        "-configuration", jdtls_path .. "/config_linux",
        "-data", vim.fn.stdpath("data") .. "/jdtls-workspace/" .. vim.fn.fnamemodify(vim.loop.cwd(), ":p:h:t"),
    },
    capabilities = capabilities,
    root_dir = function()
        return vim.fs.dirname(
            vim.fs.find({ ".git", "mvnw", "gradlew", "pom.xml", "build.gradle" }, { upward = true })[1]
        )
    end,
    settings = {
        java = {
            completion = {
                favoriteStaticMembers = {
                    "org.junit.jupiter.api.Assertions.*",
                    "org.mockito.Mockito.*",
                    "java.util.Objects.requireNonNull",
                    "java.util.Objects.requireNonNullElse",
                },
                filteredTypes = {
                    "com.sun.*",
                    "io.micrometer.shaded.*",
                    "java.awt.*",
                    "jdk.*",
                    "sun.*",
                },
            },
            import = {
                exclusions = {
                    "**/internal/**",
                },
                maven = {
                    enabled = true,
                    downloadSources = true,
                },
                gradle = {
                    enabled = true,
                },
                settings = {
                    importOrder = {
                        "java",
                        "javax",
                        "org",
                        "com",
                    },
                },
            },
            inlayHints = {
                parameterNames = { enabled = "all" },
            },
            format = {
                enabled = true,
                settings = {
                    url = jdtls_path .. "/eclipse-formatter.xml",
                },
            },
        },
    },
})

