{ inputs, flake, self }:
{ config, pkgs, lib, ... }: let
  cfg = config.banned.services.vproxy-bot;
  system = pkgs.system;
in {
  options = {
    banned.services.vproxy-bot = {
      enable = lib.mkEnableOption "enable vproxy-bot";
      websiteDomain = lib.mkOption {
        type = lib.types.str;
        example = "vproxy.store";
        description = ''vproxy website domain'';
      };
      redisPort = lib.mkOption {
        type = lib.types.port;
        example = "42069";
        description = ''redis db port'';
      };
      redisGetProxyDb = lib.mkOption {
        type = lib.types.int;
        apply = x: if x >= 0 && x <= 15 then x else throw "must be 0..15";
        default = 1;
        example = "1";
        description = ''redis db number (0-15)'';
      };
      redisPurchaseDb = lib.mkOption {
        type = lib.types.int;
        apply = x: if x >= 0 && x <= 15 then x else throw "must be 0..15";
        default = 2;
        example = "2";
        description = ''redis db number (0-15)'';
      };
      redisMasterDb = lib.mkOption {
        type = lib.types.int;
        apply = x: if x >= 0 && x <= 15 then x else throw "must be 0..15";
        default = 3;
        example = "3";
        description = ''redis db number (0-15)'';
      };
      environmentPath = lib.mkOption {
        type = lib.types.path;
        example = ''
          config.sops.secrets."name-of-service/environment".path
        '';
        description = ''
          TELEGRAM_TOKEN=
          BACKEND_URL=
          BACKEND_USERNAME=
          BACKEND_PASSWORD=
          PROD_DB_URL=
        '';
      };
    };
  };
  config = lib.mkIf cfg.enable {
    services.redis.servers."vproxy-bot-state" = {
      enable = true;
      port = cfg.redisPort;
    };
    systemd.services.vproxy-bot =
    {
      wantedBy = ["default.target"];
      after = ["network-online.target" "nginx.service" "postgresql.service" "postgrest.service"];
      requires = ["network-online.target" "nginx.service" "postgresql.service" "postgrest.service"];
      serviceConfig = {
        Type = "simple";
	EnvironmentFile = cfg.environmentPath;
        ExecStartPre = pkgs.writeShellScript "wait-for-api" ''
          echo "Waiting for API to be available..."
          for i in {1..30}; do
            if ${pkgs.curl}/bin/curl -f -s https://vproxy.cc/api/ >/dev/null 2>&1; then
              echo "API is available!"
              exit 0
            fi
            echo "API not ready, waiting... ($i/30)"
            sleep 2
          done
          echo "API still not available after 60 seconds, starting anyway..."
          exit 0
        '';
        ExecStart = "${self.packages.${system}.vproxy-bot}/bin/vproxy-bot";
        Environment = [
          "PATH=/run/current-system/sw/bin"
          "RUST_LOG=info,vproxy_bot=trace"
          "WEBSITE_DOMAIN=${cfg.websiteDomain}"
          "GET_PROXY_REDIS_URL=redis://127.0.0.1:${builtins.toString cfg.redisPort}/${builtins.toString cfg.redisGetProxyDb}"
          "PURCHASE_REDIS_URL=redis://127.0.0.1:${builtins.toString cfg.redisPort}/${builtins.toString cfg.redisPurchaseDb}"
          "MASTER_REDIS_URL=redis://127.0.0.1:${builtins.toString cfg.redisPort}/${builtins.toString cfg.redisMasterDb}"
        ];
        Restart = "always";
        RestartSec = "5s";
        
        # Shutdown configuration
        TimeoutStopSec = "30s";
        KillSignal = "SIGTERM";
        KillMode = "mixed";
        
        # Security and process management
        RemainAfterExit = false;
        StandardOutput = "journal";
        StandardError = "journal";
      };
    };
  };
}
