{
  config,
  pkgs,
  lib,
  namespace,
  ...
}:
with lib;
let
  cfg = config.${namespace}.services.actual;

  actualConfig = {
    services.actual = {
      enable = true;
      openFirewall = true;
      settings = {
        trustedProxies = [ "10.0.1.3" ];
        port = cfg.port;
        dataDir = cfg.dataDir;
        serverFiles = "${cfg.dataDir}/server-files";
        userFiles = "${cfg.dataDir}/user-files";
      };
    };

    systemd.services = {
      actual = {
        environment.ACTUAL_CONFIG_PATH = lib.mkForce "${cfg.dataDir}/config.json";
        serviceConfig = {
          ExecStart = lib.mkForce "${lib.getExe pkgs.actual-server} --config ${cfg.dataDir}/config.json";
          WorkingDirectory = lib.mkForce cfg.dataDir;
          StateDirectoryMode = lib.mkForce 700;
          DynamicUser = lib.mkForce false;
          ProtectSystem = lib.mkForce "full";
        };
      };
    };

    users.users.actual = {
      isSystemUser = true;
      group = "actual";
      home = cfg.dataDir;
    };
    users.groups.actual = { };
  };

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

  fullConfig = {
    "${namespace}".services.traefik = lib.mkIf cfg.reverseProxy.enable {
      reverseProxies = [ reverseProxyConfig ];
    };
  }
  // actualConfig;
in
{
  imports = [ ./options.nix ];

  config = mkIf cfg.enable fullConfig;
}
