{ config, lib, pkgs, ... }:

let
  cfg = config.services.nightlight;
in
{
  options.services.nightlight = {
    enable = lib.mkEnableOption "nightlight service";

    httpPort = lib.mkOption {
      type = lib.types.port;
      default = 9101;
      description = "Port for Prometheus-compatible HTTP API (remote_write and query)";
    };

    grpcPort = lib.mkOption {
      type = lib.types.port;
      default = 9091;
      description = "Port for gRPC API";
    };

    dataDir = lib.mkOption {
      type = lib.types.path;
      default = "/var/lib/nightlight";
      description = "Data directory for nightlight";
    };

    retentionDays = lib.mkOption {
      type = lib.types.int;
      default = 15;
      description = "Number of days to retain metrics data";
    };

    settings = lib.mkOption {
      type = lib.types.attrs;
      default = {};
      description = "Additional configuration settings";
    };

    package = lib.mkOption {
      type = lib.types.package;
      default = pkgs.nightlight-server or (throw "nightlight-server package not found");
      description = "Package to use for nightlight";
    };
  };

  config = lib.mkIf cfg.enable {
    # Create system user
    users.users.nightlight = {
      isSystemUser = true;
      group = "nightlight";
      description = "Nightlight service user";
      home = cfg.dataDir;
    };

    users.groups.nightlight = {};

    # Create systemd service
    systemd.services.nightlight = {
      description = "Nightlight Prometheus-Compatible Metrics Storage";
      wantedBy = [ "multi-user.target" ];
      after = [ "network.target" ];

      serviceConfig = {
        Type = "simple";
        User = "nightlight";
        Group = "nightlight";
        Restart = "on-failure";
        RestartSec = "10s";

        # State directory management
        StateDirectory = "nightlight";
        StateDirectoryMode = "0750";

        # Security hardening
        NoNewPrivileges = true;
        PrivateTmp = true;
        ProtectSystem = "strict";
        ProtectHome = true;
        ReadWritePaths = [ cfg.dataDir ];

        # Start command
        # Note: nightlight-server uses a config file, so we'll pass data-dir directly
        # The config will be auto-generated or use defaults from Config::default()
        ExecStart = "${cfg.package}/bin/nightlight-server";

        # Environment variables for configuration
        Environment = [
          "NIGHTLIGHT_HTTP_ADDR=0.0.0.0:${toString cfg.httpPort}"
          "NIGHTLIGHT_GRPC_ADDR=0.0.0.0:${toString cfg.grpcPort}"
          "NIGHTLIGHT_DATA_DIR=${cfg.dataDir}"
          "NIGHTLIGHT_RETENTION_DAYS=${toString cfg.retentionDays}"
        ];
      };
    };
  };
}
