{
  config,
  lib,
  namespace,
  ...
}:
with lib;
let
  cfg = config.${namespace}.services.home-assistant;
in
{
  config = mkIf cfg.enable {
    services = {
      # Enable and configure Mosquitto MQTT broker
      mosquitto = {
        enable = true;
        listeners = [
          {
            acl = [ "pattern readwrite #" ];
            omitPasswordAuth = true;
            settings.allow_anonymous = true;
          }
        ];
      };

      zigbee2mqtt = {
        enable = true;
        settings = {
          homeassistant = {
            enabled = config.services.home-assistant.enable;
            # Optional: Home Assistant discovery topic (default: shown below)
            # Note: should be different from [MQTT base topic](../mqtt.md) to prevent errors in HA software
            discovery_topic = "homeassistant";
            # Optional: Home Assistant status topic (default: shown below)
            status_topic = "homeassistant/status";
            # Optional: Experimental support for Home Assistant event entities, may break in the future (default: shown below) when enabled:
            # - An `event` entity will be discovered for each 'action'.
            # - The `event_type` attribute will contain the action itself, additional attributes like `button` will have further information.
            experimental_event_entities = false;
            # Optional: Home Assistant legacy action sensor (default: `false`), when enabled:
            # - Zigbee2MQTT will send an empty 'action' after one has been send
            # - A 'sensor_action' will be discovered
            legacy_action_sensor = false;
          };

          permit_join = true;
          # Web interface
          frontend = {
            port = cfg.zigbee2mqttPort;
          };
          # MQTT configuration
          mqtt = {
            base_topic = "zigbee2mqtt";
            server = "mqtt://localhost:${toString cfg.mosquittoPort}";
            # If using authentication:
            # user = "mqttuser";
            # password = "your-password";
          };
          serial = {
            port = cfg.zigbeeDevicePath;
          };
        };
      };
    };
  };
}
