{
  config,
  pkgs,
  lib,
  namespace,
  ...
}:
with lib;
let
  cfg = config.${namespace}.services.actual;
  dataDir = "/data";
  hostAddress = "10.0.1.3";
  actualUserId = config.users.users.nix-apps.uid;
  actualGroupId = config.users.groups.jallen-nas.gid;

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

    users.users.actual = {
      isSystemUser = true;
      uid = lib.mkForce actualUserId;
      group = "actual";
    };

    users.groups = {
      actual = {
        gid = lib.mkForce actualGroupId;
      };
    };

    # System packages
    environment.systemPackages = with pkgs; [
      sqlite
    ];

    # Create and set permissions for required directories
    system.activationScripts.actual-dirs = ''
      mkdir -p ${dataDir}
      chown -R actual:actual ${dataDir}
      chmod -R 0700 ${dataDir}
    '';

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

  bindMounts = {
    "${dataDir}" = {
      hostPath = cfg.dataDir;
      isReadOnly = false;
    };
  };

  # 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;
  };

  actualContainer =
    (lib.${namespace}.mkContainer {
      name = "actual";
      localAddress = cfg.localAddress;
      ports = [ cfg.port ];
      bindMounts = bindMounts;
      config = actualConfig;
    })
      { inherit lib; };

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

  config = mkIf cfg.enable fullConfig;
}
