{
  config,
  flake,
  ...
}:
let
  inherit (flake.config.people) user0;
  inherit (flake.config.services) instances;
  serviceCfg = instances.vaultwarden;
  smtpCfg = instances.smtp;
  hostCfg = instances.web;
  dns0 = instances.web.dns.provider0;
  host = serviceCfg.domains.url0;
  dns0Path = "dns/${dns0}";
  hostSecrets = "/var/lib/secrets/${serviceCfg.name}";
in
{
  microvm.vms = {
    vaultwarden = {
      autostart = true;
      restartIfChanged = true;
      config = {
        system.stateVersion = "24.05";
        time.timeZone = "America/Winnipeg";
        users.users.root.openssh.authorizedKeys.keys = flake.config.people.users.${user0}.sshKeys;
        services = {
          vaultwarden = {
            enable = true;
            dbBackend = "sqlite";
            config = {
              # Domain Configuration
              DOMAIN = "https://${host}";

              # Email Configuration
              SMTP_AUTH_MECHANISM = "Plain";
              SMTP_EMBED_IMAGES = true;
              SMTP_FROM = serviceCfg.email.address0;
              SMTP_FROM_NAME = serviceCfg.label;
              SMTP_HOST = smtpCfg.hostname;
              SMTP_PORT = smtpCfg.ports.port1;
              SMTP_SECURITY = smtpCfg.records.record1;
              SMTP_USERNAME = smtpCfg.email.address0;

              # Security Configuration
              DISABLE_ADMIN_TOKEN = false;

              # Event and Backup Management
              EVENTS_DAYS_RETAIN = 90;

              # User Features
              SENDS_ALLOWED = true;
              SIGNUPS_VERIFY = true;
              WEB_VAULT_ENABLED = true;

              # Rocket (Web Server) Settings
              ROCKET_ADDRESS = "0.0.0.0";
              ROCKET_PORT = serviceCfg.ports.port0;
            };

            # Environment file with secrets (mounted from host)
            environmentFile = "/run/secrets/env";
          };
          openssh = {
            enable = true;
            settings = {
              PasswordAuthentication = false;
              PermitRootLogin = "prohibit-password";
            };
          };
        };

        networking.firewall.allowedTCPPorts = [
          22 # SSH
          25 # SMTP
          139 # SMTP
          587 # SMTP
          2525 # SMTP
          serviceCfg.ports.port0
        ];

        systemd = {
          network = {
            enable = true;
            networks."20-lan" = {
              matchConfig.Name = "enp0s5";
              addresses = [
                { Address = "${serviceCfg.interface.ip}/24"; }
              ];
              routes = [
                {
                  Destination = "${hostCfg.localhost.address1}/0";
                  Gateway = serviceCfg.interface.gate;
                }
              ];
              dns = [
                "1.1.1.1"
                "8.8.8.8"
              ];
            };
          };

          tmpfiles.rules = [
            "Z ${serviceCfg.varPaths.path0} 0755 ${serviceCfg.name} ${serviceCfg.name} -"
            # "Z ${serviceCfg.secretPaths.path0} 0755 ${serviceCfg.name} ${serviceCfg.name} -"
          ];

        };

        systemd.services.systemd-networkd.wantedBy = [ "multi-user.target" ];

        microvm = {
          vcpu = 1;
          mem = 1024;
          hypervisor = "qemu";
          interfaces = [
            {
              type = "tap";
              id = serviceCfg.interface.id;
              mac = serviceCfg.interface.mac;
            }
            {
              type = "user";
              id = serviceCfg.interface.idUser;
              mac = serviceCfg.interface.macUser;
            }
          ];

          forwardPorts = [
            {
              from = "host";
              host.port = serviceCfg.interface.ssh;
              guest.port = 22;
            }
          ];

          shares = [
            {
              mountPoint = "/nix/.ro-store";
              proto = "virtiofs";
              source = "/nix/store";
              tag = "read_only_nix_store";
            }
            {
              mountPoint = "/var/lib/bitwarden_rs";
              proto = "virtiofs";
              source = serviceCfg.mntPaths.path0;
              tag = "${serviceCfg.name}_data";
            }
            {
              mountPoint = "/run/secrets";
              proto = "virtiofs";
              source = "/run/secrets/${serviceCfg.name}";
              tag = "host_secrets";
            }
          ];
        };
      };
    };
  };

  security.acme.certs."${host}" = {
    dnsProvider = dns0;
    environmentFile = config.sops.secrets.${dns0Path}.path;
    group = "caddy";
  };

  services.caddy.virtualHosts = {
    "${host}" = {
      extraConfig = ''
        reverse_proxy ${serviceCfg.interface.ip}:${toString serviceCfg.ports.port0} {
          header_up X-Real-IP {remote_host}
        }

        tls ${serviceCfg.ssl.cert} ${serviceCfg.ssl.key}

        encode zstd gzip
      '';
    };
  };

  users.users.caddy.extraGroups = [ "acme" ];

  systemd.tmpfiles.rules = [
    "d ${serviceCfg.mntPaths.path0} 0751 microvm wheel - -"
  ];

  sops.secrets = {
    "${serviceCfg.name}/env" = {
      owner = "root";
      mode = "0600";
    };
  };
}
