{ config, lib, ... }:

let
  cfg = config.services.nostr-relay;
  domain = config.networking.domain;
  subdomain = cfg.reverseProxy.subdomain;
  fqdn = if (cfg.reverseProxy.enable && subdomain != "") then "${subdomain}.${domain}" else domain;

  inherit (lib)
    mkDefault
    mkIf
    ;

  inherit (lib.utils)
    mkReverseProxyOption
    ;
in
{
  options.services.nostr-relay = {
    reverseProxy = mkReverseProxyOption "Nostr Relay" "nostr";
  };

  config = mkIf cfg.enable {
    services.nostr-rs-relay = {
      settings = {
        network = {
          port = mkDefault 12849;
          host = mkDefault (if cfg.reverseProxy.enable then "127.0.0.1" else "0.0.0.0");
        };
        limits = {
          max_event_size = mkDefault 65536;
          max_subscriptions = mkDefault 20;
          max_filters = mkDefault 10;
          max_subid_length = mkDefault 128;
          max_event_tags = mkDefault 2000;
          max_content_length = mkDefault 32768;
        };
        federation = {
          enabled = mkDefault true;
          max_message_size = mkDefault 1048576;
        };
        database = {
          max_query_time_ms = mkDefault 5000;
        };
      };
    };

    services.nginx.virtualHosts = mkIf cfg.reverseProxy.enable {
      "${fqdn}" = {
        enableACME = cfg.reverseProxy.forceSSL;
        forceSSL = cfg.reverseProxy.forceSSL;
        locations."/".proxyPass =
          "http://127.0.0.1:${toString config.services.nostr-rs-relay.settings.network.port}";
      };
    };
  };
}
