serviceName: {
  config,
  lib,
  ...
}:
with lib; let
  cfg = config.homelab.services.${serviceName};
  homelabCfg = config.homelab;
in {
  options.homelab.services.${serviceName}.proxy = {
    enable = mkOption {
      type = types.bool;
      description = "Enable reverse proxy for ${serviceName}";
      default = true;
    };

    subdomain = mkOption {
      type = types.str;
      default = serviceName;
    };

    enableAuth = mkOption {
      type = types.bool;
      default = false;
    };

    additionalSubdomains = mkOption {
      type = types.listOf (types.submodule {
        options = {
          subdomain = mkOption {type = types.str;};
          port = mkOption {type = types.port;};
          path = mkOption {
            type = types.str;
            default = "/";
          };
          enableAuth = mkOption {
            type = types.bool;
            default = false;
          };
        };
      });
      default = [];
    };
  };

  config = mkIf cfg.enable {
    homelab.reverseProxy.entries = mkIf cfg.proxy.enable (
      [
        {
          subdomain = cfg.proxy.subdomain;
          host = homelabCfg.hostname;
          port = cfg.port;
          path = "/";
          enableAuth = cfg.proxy.enableAuth;
          enableSSL = true;
        }
      ]
      ++ map (sub: {
        subdomain = sub.subdomain;
        host = homelabCfg.hostname;
        port = sub.port;
        path = sub.path;
        enableAuth = sub.enableAuth;
        enableSSL = true;
      })
      cfg.proxy.additionalSubdomains
    );
  };
}
