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

  opencloudConfig = {
    services.opencloud = {
      enable = true;
      port = cfg.port;
      environment = {
        OC_OIDC_ISSUER = "";
        OC_EXCLUDE_RUN_SERVICES = "idp";
        PROXY_OIDC_REWRITE_WELLKNOWN = true;
        PROXY_USER_OIDC_CLAIM = "preferred_username";
        PROXY_AUTOPROVISION_ACCOUNTS = true;
        PROXY_ROLE_ASSIGNMENT_DRIVER = "oidc";
      };
    };
  };

  # Create reverse proxy configuration using mkReverseProxy
  reverseProxyConfig = lib.${namespace}.mkReverseProxy {
    name = "cloud";
    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 ];
    };
  }
  // opencloudConfig;
in
{
  options.${namespace}.services.opencloud = {
    enable = mkEnableOption "opencloud service";

    port = mkOpt types.int 4000 "Port for opencloud 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 = mkIf cfg.enable fullConfig;
}
