{ config, lib, ... }:
let
  cfg = config.khscodes.infrastructure.kanidm-client-application;
in
{
  options.khscodes.infrastructure.kanidm-client-application = {
    enable = lib.mkEnableOption "Enables securing client credentials for oauth2 application in kanidm";
    appName = lib.mkOption {
      type = lib.types.str;
    };
    secretFile = lib.mkOption {
      type = lib.types.str;
      default = "/run/secret/kanidm/${cfg.appName}";
    };
    secretOwner = lib.mkOption {
      type = lib.types.str;
    };
    secretGroup = lib.mkOption {
      type = lib.types.str;
      default = cfg.secretOwner;
    };
    perms = lib.mkOption {
      type = lib.types.str;
      default = "0600";
    };
    reloadOrRestartUnits = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [ ];
    };
    restartUnits = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [ ];
    };
  };

  config = lib.mkIf cfg.enable {
    khscodes.services.vault-agent.templates = [
      {
        inherit (cfg) reloadOrRestartUnits restartUnits;
        contents = ''
          {{- with secret "kanidm/data/apps/${cfg.appName}" -}}
          {{ .Data.data.basic_secret }}
          {{- end -}}
        '';
        destination = cfg.secretFile;
        owner = cfg.secretOwner;
        group = cfg.secretGroup;
        perms = cfg.perms;
      }
    ];
    khscodes.infrastructure.vault-server-approle.policy = {
      "kanidm/data/apps/${cfg.appName}" = {
        capabilities = [ "read" ];
      };
    };
  };
}
