{ config, lib, pkgs, ... }:

let
  cfg = config.headscale;
in
{
  options.headscale = {
    port = lib.mkOption {
      type = lib.types.int;
    };
    domain = lib.mkOption {
      type = lib.types.str;
    };
  };

  config = {
    services = {
      headscale = {
        enable = true;
        port = cfg.port;
        # TODO: make dataDir configurable and set it to /srv/
        settings = {
          server_url = "https://${cfg.domain}";
          dns = { base_domain = "tailnet"; };
        };
      };

      nginx.virtualHosts.${cfg.domain} = {
        enableACME = true;
        forceSSL = true;
        locations."/" = {
          proxyPass = "http://localhost:${toString cfg.port}";
          proxyWebsockets = true;
        };
      };
    };
  };
}