local M = {}

local keymap = vim.keymap

local opts = { silent = true, noremap = true }

M.on_attach = function(client, bufnr)
	opts.buffer = bufnr

	-- set keybinds
	opts.desc = "See available code actions"
	keymap.set({ "n", "v" }, "<leader>ca", vim.lsp.buf.code_action, opts)

	opts.desc = "Format current file"
	keymap.set("n", "<leader>gf", vim.lsp.buf.format, opts)

	opts.desc = "Smart rename"
	keymap.set("n", "<leader>n", vim.lsp.buf.rename, opts)

	opts.desc = "Go to previous diagnostic"
	keymap.set("n", "[d", function()
		vim.diagnostic.jump({
			count = -1,
			on_jump = function()
				vim.diagnostic.open_float()
			end,
		})
	end, opts)
	keymap.set("n", "<leader>?", vim.diagnostic.open_float, opts)

	opts.desc = "Go to next diagnostic"
	keymap.set("n", "]d", function()
		vim.diagnostic.jump({
			count = 1,
			on_jump = function()
				vim.diagnostic.open_float()
			end,
		})
	end, opts)

	opts.desc = "Show documentation for what is under cursor"
	keymap.set("n", "<leader>k", vim.lsp.buf.hover, opts)

	opts.desc = "Show signature help"
	keymap.set("n", "<leader>v", vim.lsp.buf.signature_help, opts)

	opts.desc = "Restart LSP"
	keymap.set("n", "<leader>rs", ":LspRestart<CR>", opts)

	vim.opt.signcolumn = "yes" -- reserve space for diagnostics
end

M.on_attach_no_formatting = function(client, bufnr)
	M.on_attach(client, bufnr)

	client.server_capabilities.documentFormattingProvider = false
	client.server_capabilities.documentRangeFormattingProvider = false
end

-- used to enable autocompletion (assign to every lsp server config)
-- local capabilities = cmp_nvim_lsp.default_capabilities()
M.capabilities = require("blink.cmp").get_lsp_capabilities(vim.lsp.protocol.make_client_capabilities())
M.capabilities.textDocument.completion.completionItem.snippetSupport = true

return M
