{
  config,
  lib,
  ...
}:

let
  cfg = config.services.matrix-synapse;
  domain = config.networking.domain;

  inherit (lib) mkIf mkDefault;
in
{
  config = mkIf cfg.enable {
    services.livekit = {
      enable = true;
      settings.port = mkDefault 7880;
      settings.room.auto_create = mkDefault false;
      openFirewall = mkDefault true;
      keyFile = mkIf cfg.sops config.sops.templates."livekit/key".path;
    };

    services.lk-jwt-service = {
      enable = true;
      port = mkDefault 8080;
      livekitUrl = "wss://${domain}/livekit/sfu";
      keyFile = mkIf cfg.sops config.sops.templates."livekit/key".path;
    };

    systemd.services.lk-jwt-service.environment.LIVEKIT_FULL_ACCESS_HOMESERVERS = domain;

    services.nginx.virtualHosts = {
      "${domain}".locations = {
        "^~ /livekit/jwt/" = {
          priority = 400;
          proxyPass = "http://127.0.0.1:${toString config.services.lk-jwt-service.port}/";
        };
        "^~ /livekit/sfu/" = {
          priority = 400;
          proxyPass = "http://127.0.0.1:${toString config.services.livekit.settings.port}/";
          proxyWebsockets = true;
          extraConfig = ''
            proxy_send_timeout 120;
            proxy_read_timeout 120;
            proxy_buffering off;
            proxy_set_header Accept-Encoding gzip;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
          '';
        };
      };
    };

    sops = mkIf cfg.sops {
      secrets."livekit/key" = { };
      templates."livekit/key".content = ''
        API Secret:  ${config.sops.placeholder."livekit/key"}
      '';
    };
  };
}
