{
  config,
  lib,
  namespace,
  ...
}: let
  inherit (lib) mkIf;
  inherit (lib.${namespace}) getAttrByNamespace resolveDatabaseHost resolveDatabaseIP hostHasService resolveServicePort;
  inherit (config.networking) hostName;

  pgCfg = getAttrByNamespace config "${namespace}.services.storage.postgresql";

  networkCfg = getAttrByNamespace config "${namespace}.services.networking";

  isEnabled = hostHasService networkCfg.network-services hostName "grafana";
  port = resolveServicePort networkCfg.network-services "grafana" 5500;
in {
  config = mkIf isEnabled {
    services.grafana = {
      enable = true;
      settings = {
        server = {
          root_url = "https://grafana.yumeami.sh";
          domain = "grafana.yumeami.sh";
          enforce_domain = true;
          http_addr = "0.0.0.0";
          http_port = port;
        };

        users.allow_signup = false;
        "auth.anonymous".enabled = true;

        database = {
          type = "postgres";
          host = let
            ip = resolveDatabaseIP networkCfg.devices pgCfg.databases "grafana";
          in "${ip}:5600";
          name = "grafana";
          user = "grafana";
          password = "$__file{${config.sops.secrets."db/grafana".path}}";
        };

        panels.enable_alpha = true;

        security.secret_key = "SW2YcwTIb9zpOOhoPsMm";
      };

      provision = {
        datasources.settings.datasources = [
        ];
      };
    };

    systemd.services.grafana = let
      dbHost = resolveDatabaseHost pgCfg.databases "grafana";
    in
      mkIf (dbHost == config.networking.hostName) {
        after = ["postgresql.service" "pgbouncer.service"];
        requires = ["postgresql.service" "pgbouncer.service"];
        serviceConfig = {
          RestartSec = lib.mkForce "1s";
        };
      };

    sops.secrets = let
      inherit (config.users.users) grafana;
    in {
      "db/grafana" = {
        owner = grafana.name;
        group = grafana.group;
      };
    };
  };
}
