{config, ...}: let
  image = "ghcr.io/goauthentik/server:2026.2.0";

  serverIp = "10.89.0.22";
  workerIp = "10.89.0.23";

  postgresHost = "10.89.0.1";
  postgresPort = config.m3ta.ports.get "postgres";
  authentikPort = config.m3ta.ports.get "authentik";

  sharedEnv = {
    AUTHENTIK_POSTGRESQL__HOST = postgresHost;
    AUTHENTIK_POSTGRESQL__PORT = toString postgresPort;
    AUTHENTIK_POSTGRESQL__USER = "authentik";
    AUTHENTIK_POSTGRESQL__NAME = "authentik";
  };
in {
  virtualisation.oci-containers.containers = {
    "authentik-server" = {
      inherit image;
      cmd = ["server"];
      environment = sharedEnv;
      environmentFiles = [config.age.secrets.authentik-env.path];
      ports = ["127.0.0.1:${toString authentikPort}:9000"];
      volumes = [
        "authentik_media:/media"
        "authentik_templates:/templates"
      ];
      extraOptions = [
        "--add-host=postgres:${postgresHost}"
        "--ip=${serverIp}"
        "--network=web"
      ];
    };

    "authentik-worker" = {
      inherit image;
      cmd = ["worker"];
      user = "root";
      environment = sharedEnv;
      environmentFiles = [config.age.secrets.authentik-env.path];
      volumes = [
        "authentik_media:/media"
        "authentik_certs:/certs"
        "authentik_templates:/templates"
      ];
      extraOptions = [
        "--add-host=postgres:${postgresHost}"
        "--ip=${workerIp}"
        "--network=web"
      ];
    };
  };

  services.traefik.dynamicConfigOptions.http = {
    services.authentik.loadBalancer.servers = [
      {url = "http://localhost:${toString authentikPort}/";}
    ];

    routers.authentik = {
      rule = "Host(`auth.m3ta.dev`)";
      tls = {certResolver = "godaddy";};
      service = "authentik";
      entrypoints = "websecure";
    };
  };
}
