{ config, lib, ... }:

let
  cfg = config.services.burrow.openbao;
in
{
  options.services.burrow.openbao = {
    enable = lib.mkEnableOption "the Burrow OpenBao deployment";

    domain = lib.mkOption {
      type = lib.types.str;
      default = "vault.burrow.net";
      description = "Public OpenBao domain.";
    };

    listenAddress = lib.mkOption {
      type = lib.types.str;
      default = "127.0.0.1";
      description = "Local OpenBao listener address.";
    };

    port = lib.mkOption {
      type = lib.types.port;
      default = 8200;
      description = "Local OpenBao API port.";
    };

    clusterPort = lib.mkOption {
      type = lib.types.port;
      default = 8201;
      description = "Local OpenBao cluster port.";
    };

    dataDir = lib.mkOption {
      type = lib.types.str;
      default = "/var/lib/burrow/openbao";
      description = "Persistent OpenBao state directory.";
    };

    googleKmsSeal = {
      enable = lib.mkEnableOption "Google Cloud KMS seal wrapping";

      project = lib.mkOption {
        type = lib.types.str;
        default = "project-88c23ce9-918a-470a-b33";
        description = "Google Cloud project containing the seal key.";
      };

      location = lib.mkOption {
        type = lib.types.str;
        default = "global";
        description = "Google Cloud KMS key ring location.";
      };

      keyRing = lib.mkOption {
        type = lib.types.str;
        default = "burrow-identity";
        description = "Google Cloud KMS key ring name.";
      };

      cryptoKey = lib.mkOption {
        type = lib.types.str;
        default = "openbao-seal";
        description = "Google Cloud KMS crypto key name used for seal wrapping.";
      };
    };
  };

  config = lib.mkIf cfg.enable {
    systemd.tmpfiles.rules = [
      "d ${cfg.dataDir} 0700 openbao openbao - -"
      "d ${cfg.dataDir}/data 0700 openbao openbao - -"
    ];

    services.openbao = {
      enable = true;
      settings = {
        ui = true;
        api_addr = "https://${cfg.domain}";
        cluster_addr = "http://${cfg.listenAddress}:${toString cfg.clusterPort}";
        storage.file.path = "${cfg.dataDir}/data";
        listener.tcp = {
          address = "${cfg.listenAddress}:${toString cfg.port}";
          tls_disable = true;
        };
      } // lib.optionalAttrs cfg.googleKmsSeal.enable {
        seal.gcpckms = {
          project = cfg.googleKmsSeal.project;
          region = cfg.googleKmsSeal.location;
          key_ring = cfg.googleKmsSeal.keyRing;
          crypto_key = cfg.googleKmsSeal.cryptoKey;
        };
      };
    };

    services.caddy.virtualHosts."${cfg.domain}".extraConfig = ''
      encode gzip zstd
      reverse_proxy ${cfg.listenAddress}:${toString cfg.port}
    '';
  };
}
