{ pkgs, config, ... }:
let
  domain = config.khscodes.infrastructure.openbao.domain;
in
{
  config = {
    services.openbao = {
      enable = true;
      package = pkgs.openbao;
      settings = {
        ui = true;
        listener.tcp = {
          type = "tcp";
          tls_cert_file = "${config.security.acme.certs.${domain}.directory}/fullchain.pem";
          tls_key_file = "${config.security.acme.certs.${domain}.directory}/key.pem";
        };
        api_addr = "https://${domain}";
        storage.postgresql.connection_url = "postgres://openbao?host=/run/postgresql";
      };
    };
    security.acme.certs.${domain}.reloadServices = [ "openbao.service" ];

    systemd.services.openbao.after = [ "postgresql.service" ];

    # Allow openbao to read the certificate file
    users.groups.nginx.members = [ "openbao" ];

    services.postgresql = {
      enable = true;
      ensureDatabases = [ "openbao" ];
      ensureUsers = [
        {
          name = "openbao";
          ensureDBOwnership = true;
        }
      ];
    };

    services.postgresqlBackup = {
      enable = true;
      databases = [ "openbao" ];
    };

    khscodes.services.nginx.virtualHosts.${domain} = {
      locations."/" = {
        proxyPass = "https://${config.services.openbao.settings.listener.tcp.address}/";
        recommendedProxySettings = true;
      };
    };
  };
}
