{ config, lib, ... }:

let
  cfg = config.programs.nixvim;
  plugin = cfg.plugins.cmp;

  inherit (lib) mkDefault mkIf;
in
{
  programs.nixvim = {
    plugins = {
      cmp = {
        enable = mkDefault true;
        settings = {
          autoEnableSources = mkDefault true;
          experimental.ghost_text = mkDefault true;
          snippet.expand = mkDefault "luasnip";
          formatting.fields = mkDefault [
            "kind"
            "abbr"
            "menu"
          ];
          sources = [
            { name = "git"; }
            { name = "nvim_lsp"; }
            {
              name = "buffer";
              option.get_bufnrs.__raw = "vim.api.nvim_list_bufs";
              keywordLength = 3;
            }
            {
              name = "path";
              keywordLength = 3;
            }
            { name = "luasnip"; }
          ];
          mapping = {
            "<C-Space>" = "cmp.mapping.complete()";
            "<C-d>" = "cmp.mapping.scroll_docs(-4)";
            "<C-e>" = "cmp.mapping.close()";
            "<C-f>" = "cmp.mapping.scroll_docs(4)";
            "<C-CR>" = "cmp.mapping.confirm({ select = true })";
            "<S-Tab>" = "cmp.mapping(cmp.mapping.select_prev_item(), {'i', 's'})";
            "<Tab>" = "cmp.mapping(cmp.mapping.select_next_item(), {'i', 's'})";
          };
        };
      };
      cmp-cmdline = mkIf plugin.enable { enable = mkDefault false; }; # autocomplete for cmdline
      cmp_luasnip = mkIf plugin.enable { enable = mkDefault true; };
      luasnip = mkIf plugin.enable { enable = mkDefault true; };
      cmp-treesitter = mkIf (plugin.enable && cfg.plugins.treesitter.enable) { enable = mkDefault true; };
    };
  };
}
