{ pkgs, lib, config, ... }:
let
  inherit (lib) mkEnableOption;
  cfg = config.mods.server.lemmy;
  port = config.mods.server.local.ports.lemmy-api;
  port-ui = config.mods.server.local.ports.lemmy-ui;
  port-pict = config.mods.server.local.ports.pict-rs;
  hostname = "lemmy.muon.host";
  bind = "0.0.0.0";
in {
  options.mods.server.lemmy = {
    enable = mkEnableOption {
      default = false;
      description = "enables lemmy engine server";
    };
  };

  config = {
    services.lemmy = lib.mkIf cfg.enable {
      enable = true;

      ui.port = port-ui;

      settings = { inherit port hostname bind; };

      database.createLocally = true;
    };

    systemd.services.lemmy-ui = lib.mkIf cfg.enable {
      environment = lib.mkForce {
        LEMMY_UI_HOST = "${bind}:${toString port-ui}";
        LEMMY_UI_LEMMY_INTERNAL_HOST = "${bind}:${toString port}";
        LEMMY_UI_LEMMY_EXTERNAL_HOST = hostname;
        LEMMY_UI_HTTPS = "false";
        NODE_ENV = "production";
      };
    };

    services.pict-rs = lib.mkIf cfg.enable {
      enable = true;
      port = port-pict;
      address = "0.0.0.0";
    };

    # services.nginx.virtualHosts."${hostname}" = let
    #   ui = "http://10.0.0.3:${toString port-ui}";
    #   backend = "http://10.0.0.3:${toString port}";
    # in lib.mkIf config.mods.server.nginx.enable {
    #   forceSSL = true;
    #   enableACME = true;
    #   locations = {
    #     "~ ^/(api|pictrs|feeds|nodeinfo|.well-known)" = {
    #       # backend requests
    #       proxyPass = backend;
    #       proxyWebsockets = true;
    #       recommendedProxySettings = true;
    #     };
    #     "/" = {
    #       # mixed frontend and backend requests, based on the request headers
    #       extraConfig = ''
    #         set $proxpass "${ui}";
    #         if ($http_accept = "application/activity+json") {
    #           set $proxpass "${backend}";
    #         }
    #         if ($http_accept = "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"") {
    #           set $proxpass "${backend}";
    #         }
    #         if ($request_method = POST) {
    #           set $proxpass "${backend}";
    #         }

    #         # Cuts off the trailing slash on URLs to make them valid
    #         rewrite ^(.+)/+$ $1 permanent;

    #         proxy_pass $proxpass;
    #         # Proxied `Host` header is required to validate ActivityPub HTTP signatures for incoming events.
    #         # The other headers are optional, for the sake of better log data.
    #         proxy_set_header X-Real-IP $remote_addr;
    #         proxy_set_header Host $host;
    #         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #       '';
    #     };
    #   };
    # };
  };
}

