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

with lib;
let
  cfg = config.my.services.neverest;
  toml = pkgs.formats.toml { };
in
{
  options.my.services.neverest = {
    enable = mkEnableOption "neverest";
    package = mkPackageOption pkgs "neverest" { };
    frequency = mkOption {
      type = types.str;
      default = "hourly";
      description = ''
        How often to run neverest when
        `services.neverest.enable = true`.
        This value is passed to the systemd timer configuration as
        the onCalendar option. See
        {manpage}`systemd.time(7)`
        for more information about the format.
      '';
    };
    settings = mkOption {
      inherit (toml) type;
      default = { };
      apply = toml.generate "config.toml";
    };
  };


  config = mkIf cfg.enable {
    home-manager.users.moritz = {
      xdg.configFile."neverest/config.toml".source = cfg.settings;
      home.packages = [ cfg.package ];
      systemd.user.timers.neverest = {
        Unit.Description = "Run neverest";
        Timer = {
          OnCalendar = cfg.frequency;
          Persistent = true;
          RandomizedDelaySec = "10m";
        };
        Install.WantedBy = [ "timers.target" ];
      };
      systemd.user.services.neverest = {
        Unit = {
          Description = "CLI to synchronize, backup and restore emails";
        };
        Service = {
          # Lower CPU and I/O priority
          Nice = 19;
          IOSchedulingClass = "best-effort";
          IOSchedulingPriority = 7;
          IOWeight = 100;

          ExecStart = ''
            ${lib.getExe cfg.package} synchronize
          '';
        };
      };
    };
    age.secrets.email = {
      file = ../../secrets/email.age;
      owner = "1000";
    };
  };
}
