{ config
, lib
, pkgs
, ...
}:

with lib;
let
  cfg = config.my.programs.code;
in
{
  options.my.programs.code = {
    enable = mkEnableOption "code";
    package = mkOption {
      type = types.package;
      default = pkgs.vscode;
    };
    extensions = mkOption {
      type = types.listOf types.package;
      default = with pkgs.vscode-extensions; [
        bbenoist.nix
        vscodevim.vim
      ] ++ pkgs.vscode-utils.extensionsFromVscodeMarketplace [
        {
          name = "copilot-nightly";
          publisher = "GitHub";
          version = "1.86.118";
          sha256 = "04nspnmd5cfnv3m9igww6h6la6pvhdqzqmdnbm1znapxqiw2m927";
        }
        {
          name = "copilot-chat";
          publisher = "GitHub";
          version = "0.1.2023052602";
          sha256 = "0anlzzs4g7c9mmw7yxy5bgjcs0niwa3bswgvhwspf5fh8bbq5n44";
        }
      ];
    };
    wayland = mkOption {
      type = types.bool;
      default = true;
    };
  };

  config = mkIf cfg.enable {
    environment.systemPackages =
      let
        withExtensions = pkgs.vscode-with-extensions.override {
          vscode = cfg.package;
          vscodeExtensions = cfg.extensions;
        };
        maybeExtensions = if cfg.extensions == [ ] then cfg.package else withExtensions;
        withWayland = pkgs.symlinkJoin {
          name = "${maybeExtensions.name}-wayland";
          paths = [ maybeExtensions ];
          nativeBuildInputs = [ pkgs.makeWrapper ];
          postBuild = ''
            wrapProgram $out/bin/code* \
              --set NIXOS_OZONE_WL 1
          '';
        };
        final = if cfg.wayland then withWayland else maybeExtensions;
      in
      [ final ];
  };
}
