{
  description = "plebsaber.stream SvelteKit application";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05";
  };

  outputs = { self, nixpkgs }: let
    inherit (nixpkgs.lib) genAttrs;
    systems = [ "x86_64-linux" "aarch64-linux" ];
    forAllSystems = genAttrs systems;

    mkPackage = pkgs:
      pkgs.buildNpmPackage {
        pname = "plebsaber-stream";
        version = "0.0.1";
        src = pkgs.lib.cleanSourceWith {
          src = ./.;
          filter = path: type:
            !(pkgs.lib.hasInfix "/.git/" path)
            && !(pkgs.lib.hasInfix "/node_modules/" path)
            && !(pkgs.lib.hasInfix "/.svelte-kit/" path);
        };

        nodejs = pkgs.nodejs_22;
        npmDepsHash = "sha256-q2C2NBxjVoxA6XFEMjGZcHAujp5OTiz7llhq3aRFiY0=";
        npmBuildScript = "build";
        NODE_OPTIONS = "--dns-result-order=ipv4first";

        nativeBuildInputs = [ pkgs.makeWrapper ];

        installPhase = ''
          runHook preInstall
          mkdir -p $out/app
          cp -r build $out/app/
          makeWrapper ${pkgs.nodejs_22}/bin/node $out/bin/plebsaber-stream \
            --set NODE_ENV production \
            --add-flags "$out/app/build/index.js"
          runHook postInstall
        '';

        meta = {
          description = "plebsaber.stream SvelteKit application";
          mainProgram = "plebsaber-stream";
        };
      };
  in rec {
    packages = forAllSystems (system: let
      pkgs = import nixpkgs { inherit system; };
      pkg = mkPackage pkgs;
    in {
      plebsaber-stream = pkg;
      default = pkg;
    });

    overlays.default = final: prev: {
      plebsaber-stream = self.packages.${prev.stdenv.hostPlatform.system}.plebsaber-stream;
    };

    nixosModules.default = { config, lib, pkgs, ... }:
      let
        inherit (lib) mkEnableOption mkIf mkOption types;
        cfg = config.services.plebsaber-stream;
        system = pkgs.stdenv.hostPlatform.system;
        defaultPackage = self.packages.${system}.plebsaber-stream;
      in {
        options.services.plebsaber-stream = {
          enable = mkEnableOption "plebsaber.stream SvelteKit service";

          package = mkOption {
            type = types.package;
            default = defaultPackage;
            defaultText = "self.packages.${system}.plebsaber-stream";
            description = "Derivation that provides the plebsaber.stream server.";
          };

          port = mkOption {
            type = types.port;
            default = 8037;
            description = "HTTP listen port for the Node server.";
          };

          stateDirectory = mkOption {
            type = types.str;
            default = "plebsaber-stream";
            description = "Name of the state directory managed by systemd.";
          };

          environment = mkOption {
            type = types.attrsOf types.str;
            default = {};
            description = "Additional environment variables for the service.";
          };

          environmentFile = mkOption {
            type = types.nullOr types.path;
            default = null;
            description = "Optional environment file consumed by systemd.";
          };
        };

        config = mkIf cfg.enable {
          systemd.services.plebsaber-stream = {
            description = "plebsaber.stream SvelteKit service";
            wantedBy = [ "multi-user.target" ];
            after = [ "network-online.target" ];
            wants = [ "network-online.target" ];

            environment = {
              NODE_ENV = "production";
              PORT = builtins.toString cfg.port;
            } // cfg.environment;

            serviceConfig = {
              Type = "simple";
              ExecStart = "${cfg.package}/bin/plebsaber-stream";
              DynamicUser = true;
              StateDirectory = cfg.stateDirectory;
              WorkingDirectory = "/var/lib/${cfg.stateDirectory}";
              Restart = "on-failure";
              RestartSec = 3;
            } // lib.optionalAttrs (cfg.environmentFile != null) {
              EnvironmentFile = cfg.environmentFile;
            };
          };
        };
      };
  };
}

