{ lib, config, ... }:
let
  cfg = config.khscodes.vault;
in
{
  options.khscodes.vault = {
    enable = lib.mkEnableOption "Enables the openbao provider";
    domain = lib.mkOption {
      type = lib.types.str;
    };
    policy = lib.mkOption {
      type = lib.types.attrsOf (
        lib.khscodes.mkSubmodule {
          options = {
            name = lib.mkOption {
              type = lib.types.str;
              description = "Name of the policy";
            };
            policy = lib.mkOption {
              type = lib.types.lines;
              description = "The policy";
            };
          };
          description = "vault_policy";
        }
      );
    };
  };

  imports = [
    ./approle_auth_backend.nix
    ./output.nix
    ./mount.nix
    ./ssh_secret_backend.nix
    ./pki_secret_backend.nix
  ];

  config = lib.mkIf cfg.enable {
    provider.vault = {
      address = "https://${cfg.domain}";
    };
    terraform.required_providers.vault = {
      source = "hashicorp/vault";
      version = "5.0.0";
    };
    resource.vault_policy = lib.mapAttrs' (name: value: {
      name = lib.khscodes.sanitize-terraform-name name;
      value = value;
    }) cfg.policy;
  };
}
