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

let
  cfg = config.permafrost.foundry;
  ACMEEnabled = config.permafrost.acme.enable;
in
{
  options.permafrost.foundry = {
    enable = lib.mkEnableOption "foundry nixos module";
  };

  config = lib.mkIf cfg.enable (lib.mkMerge [
    {
      permafrost.nginx.enable = lib.mkDefault true;
    }
    {
      users.groups.foundry = { };
      users.users.foundry = {
        group = "foundry";
        isSystemUser = true;
        description = "foundryvtt user";
      };

      systemd.services.foundry =
        let
          mainPath = "/home/foundry/foundryvtt/resources/app/main.js";
          dataPath = "/home/foundry/foundrydata";
        in
        {
          description = "foundryvtt service";
          enable = true;
          after = [ "network.target" ];
          wantedBy = [ "multi-user.target" ];
          serviceConfig = {
            User = "foundry";
            Restart = "always";
            WorkingDirectory = "/home/foundry/foundryvtt";
            ExecStart = "${lib.getExe pkgs.nodejs_20} ${mainPath} --dataPath=${dataPath}";
          };
        };
    }
    {
      services.nginx.virtualHosts."scarlet.zynh.me" = {
        serverName = "scarlet.zynh.me";
        forceSSL = lib.mkIf ACMEEnabled true;
        useACMEHost = lib.mkIf ACMEEnabled "permafrost";
        locations."/" = {
          extraConfig = /* nginx */ ''
            # Set proxy headers
            proxy_set_header Host              $host;
            proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # These are important to support WebSockets
            proxy_set_header Upgrade    $http_upgrade;
            proxy_set_header Connection "Upgrade";
          '';
          proxyPass = "http://localhost:30000";
        };
      };
    }
    {
      permafrost.acme.certDomains = lib.mkIf ACMEEnabled [ "ddbimporter.zynh.me" ];
      services.nginx.virtualHosts."ddbimporter.zynh.me" = {
        forceSSL = true;
        useACMEHost = lib.mkIf ACMEEnabled "permafrost";
        serverName = "ddbimporter.zynh.me";
        locations."/".proxyPass = "http://localhost:3232";
      };
    }
  ]);
}