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

  paperlessConfig = lib.${namespace}.mkModule {
    inherit config name;
    serviceName = "${name}-web";
    description = "paperless";
    options = { };
    moduleConfig = {
      # Enable paperless service
      services.paperless = {
        enable = true;
        package = pkgs.paperless-ngx;
        port = cfg.port;
        # user = "nix-apps";
        address = cfg.listenAddress;
        dataDir = "${cfg.configDir}/paperless";
        # passwordFile = "${cfg.configDir}/paperless/paperless-passwords";
        environmentFile = config.sops.templates."paperless.env".path;
        domain = "paperless.mjallen.dev";
        database.createLocally = true;
      };
    };
  };

  aiCfg = config.${namespace}.services."paperless-ai";
  paperlessAiConfig = lib.${namespace}.mkModule {
    inherit config;
    name = "paperless-ai";
    serviceName = "podman-paperless-ai";
    description = "paperless-ai";
    options = { };
    moduleConfig = {
      virtualisation.oci-containers.containers."paperless-ai" = {
        autoStart = true;
        image = "clusterzx/paperless-ai";
        ports = [
          "${toString aiCfg.port}:3000"
        ];
        volumes = [ "${aiCfg.configDir}/paperless-ai:/app/data" ];
        environment = {
          PUID = aiCfg.puid;
          PGID = aiCfg.pgid;
          TZ = aiCfg.timeZone;
        };
      };
    };
  };
in
{
  imports = [
    paperlessConfig
    paperlessAiConfig
  ];
}
