{
  config,
  lib,
  ...
}:
with lib; let
  serviceName = "caddy";
  cfg = config.homelab.services.${serviceName};
  homelabCfg = config.homelab;

  allProxyEntries = homelabCfg.reverseProxy.global.allEntries;
  generateVirtualHosts = entries:
    listToAttrs (map (entry: {
        name = entry._fqdn;
        value = {
          extraConfig = ''
            reverse_proxy ${entry._upstream}
          '';
        };
      })
      entries);
in {
  imports = [
    (import ../lib/features/monitoring.nix serviceName)
    (import ../lib/features/logging.nix serviceName)
  ];

  # Core service options
  options.homelab.services.${serviceName} = {
    enable = mkEnableOption "Caddy web server";

    description = mkOption {
      type = types.str;
      default = "Caddy web server";
    };

    openFirewall = mkOption {
      type = types.bool;
      default = true;
      description = ''
        Whether to open the ports specified in `port` and `webPort` in the firewall.
      '';
    };

    systemdServices = mkOption {
      type = types.listOf types.str;
      default = [
        "caddy.service"
        "caddy"
      ];
      description = "Systemd services to monitor";
    };
  };

  # Service configuration with smart defaults
  config = mkIf cfg.enable (mkMerge [
    {
      services.caddy = {
        enable = true;

        virtualHosts = generateVirtualHosts allProxyEntries;
      };
      networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [80 443];
    }
    {
      # homelab.services.${serviceName}.monitoring = {
      #   metrics.path = "/metrics";

      #   healthCheck.path = "/healthz";
      #   healthCheck.conditions = ["[STATUS] == 200" "[RESPONSE_TIME] < 1000"];

      #   extraLabels = {
      #     component = "example";
      #   };
      # };
    }
    {
      # homelab.services.${serviceName}.logging = {
      #   files = ["/var/log/example/log.log"];
      #   # parsing = {
      #   #   regex = "^ts=(?P<timestamp>[^ ]+) caller=(?P<caller>[^ ]+) level=(?P<level>\\w+) msg=\"(?P<message>[^\"]*)\"";
      #   #   extractFields = ["level" "caller"];
      #   # };
      #   extraLabels = {
      #     component = "example";
      #     application = "example";
      #   };
      # };
    }
    {
      # homelab.services.${serviceName}.proxy = {
      #   enableAuth = true;
      # };
    }
  ]);
}
