{ services, pkgs, lib, ... }:

{
  architect.firewall = {
    openTCP = [ 80 443 ];
  };

  services.nginx = {
    enable = true;
    package = pkgs.nginx;
    recommendedGzipSettings = true;
    recommendedOptimisation = true;
    recommendedProxySettings = true;
    recommendedTlsSettings = true;
    
    virtualHosts."architect.devs.giugl.io" = {
      default = true;
      enableACME = true;
      forceSSL = true;
      root = "/var/lib/nginx/error_pages";
      extraConfig = "error_page 404 /index.htm;";

      locations = {
        "/" = { return = "404"; };

        "/index.htm" = { };

        "/style.css" = { };

        "/wat.jpg" = { };
      };
    };

    # appendHttpConfig =
    #   let
    #     extraPureLuaPackages = with pkgs.luajitPackages; [
    #       lua-resty-openidc
    #       lua-resty-http
    #       lua-resty-session
    #       lua-resty-jwt
    #       lua-resty-openssl
    #     ];
    #     luaPath = pkg: "${pkg}/share/lua/5.1/?.lua";
    #     makeLuaPath = lib.concatMapStringsSep ";" luaPath;
    #   in
    #   ''
    #     # https://stackoverflow.com/questions/38931468/nginx-reverse-proxy-error14077438ssl-ssl-do-handshake-failed
    #     proxy_ssl_server_name on;

    #     lua_package_path '${makeLuaPath extraPureLuaPackages};;';
    #     lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
    #     lua_ssl_verify_depth 5;

    #     # cache for OIDC discovery metadata
    #     lua_shared_dict discovery 1m;
    #     lua_shared_dict jwks 1m;

    #     # https://github.com/openresty/lua-resty-redis/issues/159
    #     resolver local=on ipv6=off;

    #     init_worker_by_lua_block {
    #       function check_role (res, role)
    #         if res.user.roles == nil then
    #           return false
    #         end

    #         for _,v in pairs(res.user.roles) do
    #           if string.lower(v) == role then
    #             return true
    #           end
    #         end

    #         return false
    #       end
        
    #       function is_ip_whitelisted(ip, whitelist)
    #         for _, x in ipairs(whitelist) do
    #           if ip == x then
    #             return true
    #           end
    #         end
            
    #         return false
    #       end
    #     }
    #   '';

    appendConfig = ''
      worker_processes 24;
    '';
  };
  
  users.groups.acme.members = [ "nginx" ];
}