-- File: lua/user/null-ls.lua

local status_ok, null_ls = pcall(require, "null-ls")
if not status_ok then
    vim.notify("null-ls.nvim not found — run :PackerSync", vim.log.levels.WARN)
    return
end

-- Define builtins for formatting
local formatting = null_ls.builtins.formatting

-- Configure null-ls
local sources = {
	formatting.prettier, -- Use prettier for formatting (JavaScript, TypeScript, etc.)
	formatting.gofumpt, -- Go: stricter gofmt
	formatting.goimports, -- Go: organize imports + format
	formatting.black, -- Use black for Python formatting
	formatting.stylua, -- Use stylua for Lua formatting
	formatting.google_java_format.with({
		command = "java",
		args = { "-jar", "/home/prabhat/.config/nvim/jars/google-java-format.jar", "-" },
		extra_args = { "--aosp" }, -- optional: use AOSP style formatting
		--command = "google-java-format", -- specify command if not in PATH
	}),
	-- Kotlin formatting via ktfmt — runs as separate JVM, no OOM risk.
	-- Custom formatter (not in null-ls builtins for this version).
	{
		name = "ktfmt",
		method = null_ls.methods.FORMATTING,
		filetypes = { "kotlin" },
		generator = null_ls.generator({
			command = "java",
			args = { "-jar", "/home/prabhat/.config/nvim/jars/ktfmt.jar", "-" },
			to_stdin = true,
		}),
	},
	-- YAML formatting via yamlfmt (Mason: yamlfmt)
	formatting.yamlfmt,
	-- XML formatting via xmllint (system package: libxml2-utils)
	formatting.xmllint,
	-- Add other formatters based on your needs
}

null_ls.setup({
 sources = sources,
    on_attach = function(client, bufnr)
        if client.server_capabilities.documentFormattingProvider then
            local lsp_format_group = vim.api.nvim_create_augroup("LspFormatting", { clear = true })
            vim.api.nvim_create_autocmd("BufWritePre", {
                group = lsp_format_group,
                buffer = bufnr,
                callback = function()
                    local view = vim.fn.winsaveview()
                    vim.lsp.buf.format()
                    vim.fn.winrestview(view)
                end,
            })
        end
    end,
})
