{ config, lib, namespace, ... }:
let
  inherit (lib.${namespace}) mkOpt mkReverseProxyOpt;
  cfg = config.${namespace}.services.matrix;

  matrixConfig = {
    services = {
      matrix-conduit = {
        enable = true;
        settings = {
          global = {
            server_name = "mjallen.dev";
            address = "0.0.0.0";
            port = cfg.port;
            allow_registration = false;
            well_known = {
              client = "https://matrix.mjallen.dev";
              server = "matrix.mjallen.dev:443";
            };
          };
        };
      };
    };

    networking = {
      firewall = {
        enable = true;
        allowedTCPPorts = [ cfg.port 8448 ];
        allowedUDPPorts = [ cfg.port 8448 ];
      };
      # Use systemd-resolved inside the container
      # Workaround for bug https://github.com/NixOS/nixpkgs/issues/162686
      useHostResolvConf = lib.mkForce false;
    };
    services.resolved.enable = true;
  };

  bindMounts = {
    "/var/lib" = {
      hostPath = cfg.dataDir;
      isReadOnly = false;
    };
  };

  # Create reverse proxy configuration using mkReverseProxy
  reverseProxyConfig = lib.${namespace}.mkReverseProxy {
    name = "matrix";
    subdomain = cfg.reverseProxy.subdomain;
    url = "http://${cfg.localAddress}:${toString cfg.port}";
    middlewares = cfg.reverseProxy.middlewares;
  };

  matrixContainer = (lib.${namespace}.mkContainer {
    name = "matrix-conduit";
    localAddress = cfg.localAddress;
    port = cfg.port;
    bindMounts = bindMounts;
    config = matrixConfig;
  }) { inherit lib; };

  fullConfig = {
    ${namespace}.services.traefik = lib.mkIf cfg.reverseProxy.enable {
      reverseProxies = [ reverseProxyConfig ];
    };
  } // matrixContainer;
in
with lib;
{
  options.${namespace}.services.matrix = {
    enable = mkEnableOption "matrix service";

    port = mkOpt types.int 8008 "Port for matrix to be hosted on";

    localAddress = mkOpt types.str "127.0.0.1" "local address of the service";

    dataDir = mkOpt types.str "" "Path to the data dir";

    reverseProxy = mkReverseProxyOpt;
  };

  config = lib.mkIf cfg.enable fullConfig;
}