{ inputs, config, ... }:
let
  mattermost = config.services.mattermost;
in
{
  imports = [
    "${inputs.self}/nix/profiles/nixos/khs-openstack-server.nix"
  ];
  services.postgresql = {
    enable = true;
    ensureDatabases = [ "mattermost" ];
    ensureUsers = [
      {
        name = "mattermost";
        ensureDBOwnership = true;
      }
    ];
  };
  services.mattermost = {
    enable = true;
    siteName = "chat.kaareskovgaard.net";
    siteUrl = "https://chat.kaareskovgaard.net";
    database = {
      create = false;
    };
    telemetry = {
      enableSecurityAlerts = false;
      enableDiagnostics = false;
    };
    settings = {
      EmailSettings = {
        EnableSignUpWithEmail = false;
        EnableSignInWithEmail = true;
        EnableSignInWithUsername = false;
      };
    };
  };
  khscodes = {
    infrastructure.khs-openstack-instance = {
      enable = true;
      flavor = "m.small";
      network = {
        ipv4Cidr = "172.24.1.0/24";
      };
    };
    services.nginx = {
      enable = true;
      virtualHosts."chat.kaareskovgaard.net" = {
        rateLimit.burst = 100;
        locations."/" = {
          proxyPass = "http://127.0.0.1:${toString mattermost.port}";
          proxyWebsockets = true;
          recommendedProxySettings = true;
        };
      };
    };
    services.vault-agent.templates = [
      {
        contents = ''
          {{- with secret "kanidm/data/apps/mattermost" -}}
          MM_OPENIDSETTINGS_SECRET={{ .Data.data.basic_secret }}
          {{- end -}}
        '';
        destination = "/run/mattermost/env";
        owner = "mattermost";
        group = "mattermost";
        perms = "0600";
        reloadOrRestartUnits = [ "mattermost.service" ];
      }
    ];
    infrastructure.vault-server-approle.policy = {
      "kanidm/data/apps/mattermost" = {
        capabilities = [ "read" ];
      };
    };
  };
  khscodes.networking.fqdn = "chat.kaareskovgaard.net";
  system.stateVersion = "25.05";
}
