{ config, lib, ... }:

let
  cfg = config.services.loki;
  nginxCfg = config.services.nginx;
  basePath = "/var/lib/loki";
in
{
  age.secrets.loki-basicauth = {
    file = ./loki-basicauth.age;
    owner = nginxCfg.user;
    inherit (nginxCfg) group;
  };

  services.loki = {
    enable = true;
    configuration = {
      auth_enabled = false;
      server = {
        http_listen_address = "127.0.0.1";
        http_listen_port = 3100;
      };
      common = {
        path_prefix = basePath;
      };
      ingester = {
        lifecycler = {
          address = "127.0.0.1";
          ring = {
            kvstore = {
              store = "inmemory";
            };
            replication_factor = 1;
          };
        };
      };
      compactor = {
        working_directory = "${basePath}/compactor";
      };
      schema_config = {
        configs = [
          {
            from = "2025-02-04";
            store = "tsdb";
            object_store = "filesystem";
            schema = "v13";
            index = {
              prefix = "index_";
              period = "24h";
            };
          }
        ];
      };
      storage_config = {
        filesystem = {
          directory = "${basePath}/chunks";
        };
        tsdb_shipper = {
          active_index_directory = "${basePath}/tsdb-index";
          cache_location = "${basePath}/tsdb-cache";
        };
      };

      # Лимиты
      limits_config = {
        reject_old_samples = true;
        reject_old_samples_max_age = "168h"; # Максимальный возраст логов (7 дней)
      };
    };
  };

  systemd.tmpfiles.rules = lib.mkIf cfg.enable [
    "d ${basePath} 0755 ${cfg.user} ${cfg.group} -"
  ];

  services.nginx.virtualHosts."loki.pleshevski.ru" = lib.mkIf cfg.enable {
    enableACME = true;
    forceSSL = true;
    locations."/" = let inherit (cfg.configuration.server) http_listen_port http_listen_address; in {
      proxyPass = "http://${http_listen_address}:${toString http_listen_port}";
      proxyWebsockets = true;
      basicAuthFile = config.age.secrets.loki-basicauth.path;
    };
  };
}