# scripts/validate-config.nix
{
  lib,
  pkgs,
}: let
  inherit (lib) types mkOption;

  # Validation functions
  validateBackupJob = job: let
    errors =
      []
      ++ (
        if job.paths == []
        then ["Backup job '${job.name}' has no paths defined"]
        else []
      )
      ++ (
        if !(builtins.elem job.backend ["restic" "borg" "rclone"])
        then ["Invalid backup backend: ${job.backend}"]
        else []
      )
      ++ (
        if job.schedule == ""
        then ["Backup job '${job.name}' has no schedule defined"]
        else []
      );
  in
    errors;

  validateMonitoringEndpoint = endpoint: let
    errors =
      []
      ++ (
        if endpoint.port < 1 || endpoint.port > 65535
        then ["Invalid port ${toString endpoint.port} for endpoint '${endpoint.name}'"]
        else []
      )
      ++ (
        if endpoint.jobName == ""
        then ["Monitoring endpoint '${endpoint.name}' has no job name"]
        else []
      );
  in
    errors;

  validateReverseProxyEntry = entry: let
    errors =
      []
      ++ (
        if entry.subdomain == ""
        then ["Reverse proxy entry has no subdomain defined"]
        else []
      )
      ++ (
        if entry.port < 1 || entry.port > 65535
        then ["Invalid port ${toString entry.port} for subdomain '${entry.subdomain}'"]
        else []
      );
  in
    errors;

  validateGlobalConfig = config: let
    backupErrors = lib.flatten (map validateBackupJob config.backups.jobs);
    monitoringErrors = lib.flatten (map validateMonitoringEndpoint config.monitoring.endpoints);
    proxyErrors = lib.flatten (map validateReverseProxyEntry config.reverseProxy.entries);
    allErrors = backupErrors ++ monitoringErrors ++ proxyErrors;
  in
    if allErrors == []
    then {
      valid = true;
      errors = [];
    }
    else {
      valid = false;
      errors = allErrors;
    };
in {
  inherit validateGlobalConfig validateBackupJob validateMonitoringEndpoint validateReverseProxyEntry;
}
