{ inputs, flake, self }:
{ config, pkgs, lib, ... }: let
  system = pkgs.system;
  cfg = config.banned.services.vproxy-web;
in {
  options = {
    banned.services.vproxy-web = {
      enable = lib.mkEnableOption "enable vproxy-web";
      environmentPath = lib.mkOption {
        type = lib.types.path;
        example = ''
          config.sops.secrets."name-of-service/environment".path
        '';
        description = ''
          BACKEND_URL=
          BACKEND_USERNAME=
          BACKEND_PASSWORD=
        '';
      };
    };
  };
  config = lib.mkIf cfg.enable {

    services.nginx.virtualHosts = {
      "vproxy.cc" = {
        serverName = "vproxy.cc";
        locations."/" = {
          extraConfig = ''
            proxy_pass http://127.0.0.1:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
          '';
        };
      };
    };
    systemd.services.vproxy-web =
    {
      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 = pkgs.writeShellScript "vproxy-web-start" ''
          export LEPTOS_SITE_ADDR="0.0.0.0:3000"
          exec ${self.packages.${system}.vproxy-web-new}/bin/vproxy-web
        '';
        Restart = "always";
        RestartSec = "5s";
      };
    };
  };
}
