{
  config,
  lib,
  namespace,
  ...
}:
let
  cfg = config.${namespace}.services.home-assistant;
in
{
  imports = [ ./options.nix ];

  config = lib.mkIf cfg.enable {
    # This bypasses the component validation and places it directly in HA's data directory
    system.activationScripts.installCustomComponents = ''
      chown -R hass:hass ${config.services.home-assistant.configDir}
      chmod -R 750 ${config.services.home-assistant.configDir}
    '';

    services = {
      matter-server = {
        enable = true;
        port = 5580;
      };
      postgresql = {
        enable = false;
        ensureDatabases = [ "hass" ];
        ensureUsers = [
          {
            name = "hass";
            ensureDBOwnership = true;
          }
        ];
      };
    };

    networking.firewall.allowedTCPPorts = [
      cfg.mosquittoPort
      cfg.zigbee2mqttPort
      8095 # music-assistant
      8097 # home-assistant
      5580 # matter-server
    ];
  };
}
