{
  config,
  lib,
  namespace,
  ...
}:
with lib;
let
  cfg = config.${namespace}.services.gitea;
  rootUrl = "https://gitea.mjallen.dev/";
  mailerPasswordFile = config.sops.secrets."jallen-nas/gitea/mail-key".path;
  metricsTokenFile = config.sops.secrets."jallen-nas/gitea/metrics-key".path;

  # Create reverse proxy configuration using mkReverseProxy
  reverseProxyConfig = lib.${namespace}.mkReverseProxy {
    name = "gitea";
    subdomain = cfg.reverseProxy.subdomain;
    url = "http://${cfg.localAddress}:${toString cfg.httpPort}";
    middlewares = cfg.reverseProxy.middlewares;
  };

  traefik = {
    "${namespace}".services.traefik = lib.mkIf cfg.reverseProxy.enable {
      reverseProxies = [ reverseProxyConfig ];
    };
  };
in
{
  imports = [ ./options.nix ];
  config =
    mkIf cfg.enable {
      services.gitea = {
        enable = true;
        stateDir = cfg.dataDir;
        user = "nix-apps";
        group = "jallen-nas";
        mailerPasswordFile = mailerPasswordFile;
        metricsTokenFile = metricsTokenFile;
        settings = {
          server = {
            DOMAIN = "jallen-nas";
            HTTP_ADDR = "0.0.0.0";
            HTTP_PORT = cfg.httpPort;
            PROTOCOL = "http";
            ROOT_URL = rootUrl;
            START_SSH_SERVER = true;
            SSH_PORT = cfg.sshPort;
          };
          service = {
            REGISTER_EMAIL_CONFIRM = false;
            ENABLE_CAPTCHA = false;
            DISABLE_REGISTRATION = true;
            ENABLE_OPENID_SIGNIN = false;
            ENABLE_LDAP_SIGNIN = false;
            ENABLE_SSH_SIGNIN = true;
            ENABLE_BUILTIN_SSH_SERVER = true;
            ENABLE_REVERSE_PROXY_AUTHENTICATION = true;
          };
        };
      };
    }
    // traefik;
}
