{ config, lib, pkgs, ... }:
let
  homeserverDomain = config.services.matrix-synapse.settings.server_name;
in
{
  services.postgresql = {
    enable = true;
    ensureUsers = [{
      name = "mautrix-telegram";
      ensureDBOwnership = true;
    }];
    ensureDatabases = [ "mautrix-telegram" ];
  };

  age.secrets.mautrix-telegram = {
    file = ../../../../secrets/nuc/mautrix-telegram/env.age;
    owner = config.systemd.services.matrix-synapse.serviceConfig.User;
  };

  services.mautrix-telegram = {
    enable = true;

    environmentFile = config.age.secrets.mautrix-telegram.path;
    registerToSynapse = true;

    settings = {
      homeserver = {
        address = "http://[::1]:8008";
        domain = homeserverDomain;
      };

      appservice = rec {
        # Use postgresql instead of sqlite
        database = "postgresql:///mautrix-telegram?host=/run/postgresql";
        port = 8082;
        address = "http://localhost:${toString port}";
      };

      bridge = {
        relaybot.authless_portals = false;
        permissions = {
          "@rouven:${homeserverDomain}" = "admin";
        };
        relay_user_distinguishers = [ ];
      };
    };
  };
}

