local wezterm = require("wezterm")
local util = require("util") -- Ensure you have your utility module available
local M = {}

-- Define the kill_workspace function
M.kill_workspace = function(workspace)
	print("Killing workspace:", workspace) -- Debugging output
	local success, stdout = wezterm.run_child_process({ "/opt/homebrew/bin/wezterm", "cli", "list", "--format=json" })

	if success then
		local json = wezterm.json_parse(stdout)
		if not json then
			return
		end

		local workspace_panes = util.filter(json, function(p)
			return p.workspace == workspace
		end)

		for _, p in ipairs(workspace_panes) do
			wezterm.run_child_process({
				"/opt/homebrew/bin/wezterm",
				"cli",
				"kill-pane",
				"--pane-id=" .. p.pane_id,
			})
		end
	end
end

-- Function to set key bindings
local function configure_keybindings()
	return {
		{
			key = "d",
			mods = "CTRL | SHIFT",
			action = wezterm.action_callback(function(window)
				local w = window:active_workspace()
				M.kill_workspace(w) -- Use the correct reference to M.kill_workspace
			end),
		},
	}
end

-- Set the key bindings in the configuration
wezterm.on("update-config", function(conf)
	conf.keys = configure_keybindings()
end)

return M
