{ config, pkgs, lib, ...}:
let
  autoCfg = config.autoCfg;
in
{

  options.autoCfg= {
      userName = lib.mkOption {
          type = lib.types.str;
          description = "username for enabling sudo-less system updates";
      };
      flakePath = lib.mkOption {
          type = lib.types.str;
          description = "Absolute path to the NixOS flake configuration directory";
      };
      hostName = lib.mkOption {
          type = lib.types.str;
          description = "Hostname for the nixos-rebuild flake target";
      };
  };

  config = {
    # Make sure the user can use sudo for nixos-rebuild without password
    security.sudo.extraRules = [
      {
        users = [ autoCfg.userName ];
        commands = [
          {
            command = "${pkgs.nixos-rebuild}/bin/nixos-rebuild";
            options = [ "NOPASSWD" ];
          }
        ];
      }
    ];

    # Disable builtin auto-update because we hand-rollin
    system.autoUpgrade.enable = false;

    # Define user services and timers
    systemd.user.services.nixos-flake-update = {
      description = "Update NixOS Flake Inputs";
      serviceConfig = {
        Type = "oneshot";
        ExecStart = pkgs.writeShellScript "nixos-flake-update.sh" ''
          set -e
          cd ${autoCfg.flakePath}
        
          echo "Updating flake inputs..."
          ${pkgs.nix}/bin/nix flake lock \
            --update-input nixpkgs \
            --update-input nixpkgs-unstable
          
          echo "Flake inputs updated successfully"
        '';
      };
      environment = {
        NIX_CONFIG = "experimental-features = nix-command flakes";
      };
    };

    systemd.user.services.nixos-rebuild = {
      description = "Rebuild NixOS";
      serviceConfig = {
        Type = "oneshot";
        ExecStart = pkgs.writeShellScript "nixos-rebuild.sh" ''
          set -e
        
          echo "Rebuilding NixOS..."
          ${pkgs.nixos-rebuild}/bin/nixos-rebuild switch \
            -L \
            --flake ${autoCfg.flakePath}#${autoCfg.hostName}
          
          echo "NixOS rebuild completed successfully"
        '';
      };
    };

    # Combined service that runs both update and rebuild in sequence
    systemd.user.services.nixos-upgrade = {
      description = "Update and Rebuild NixOS";
      serviceConfig = {
        Type = "oneshot";
        # Use a shell script to run both operations in sequence
        ExecStart = pkgs.writeShellScript "nixos-complete-upgrade.sh" ''
          set -e
        
          echo "Starting complete NixOS upgrade process..."
        
          # First update the flake inputs
          systemctl --user start nixos-flake-update.service
          systemctl --user status nixos-flake-update.service --no-pager
        
          # Then rebuild if the update was successful
          if [ $? -eq 0 ]; then
            systemctl --user start nixos-rebuild.service
            systemctl --user status nixos-rebuild.service --no-pager
          else
            echo "Flake update failed, skipping rebuild"
            exit 1
          fi
        
          echo "Complete NixOS upgrade process finished"
        '';
      };
      environment = {
        NIX_CONFIG = "experimental-features = nix-command flakes";
      };
    };

    # Timer to run the upgrade service
    systemd.user.timers.nixos-upgrade = {
      description = "Timer for NixOS Upgrade";
      wantedBy = [ "timers.target" ];
      timerConfig = {
        OnCalendar = "12:00";
        RandomizedDelaySec = "45min";
        Persistent = true; # Run immediately if last run was missed
      };
    };
  };
}
