# ABOUTME: Periodic batch job for PhaseFlow Garmin sync.
# ABOUTME: Triggers daily sync at 6 AM to fetch fitness data and generate training recommendations.

job "phaseflow-cron" {
  datacenters = ["alo"]
  type        = "batch"

  periodic {
    crons            = ["0 8 * * *"]
    prohibit_overlap = true
    time_zone        = "Europe/Lisbon"
  }

  group "garmin-sync" {
    task "trigger" {
      driver = "raw_exec"

      config {
        command = "/bin/sh"
        args    = ["local/script.sh"]
      }

      template {
        destination = "local/script.sh"
        data        = <<EOH
set -e
RESPONSE=$(/run/current-system/sw/bin/curl -s -w "\n%%{http_code}" -X POST \
  -H "Authorization: Bearer $CRON_SECRET" \
  https://phaseflow.v.paler.net/api/cron/garmin-sync)

HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | sed '$d')

echo "$BODY"

if [ "$HTTP_CODE" -ge 400 ]; then
  echo "HTTP error: $HTTP_CODE" >&2
  exit 1
fi
EOH
      }

      template {
        destination = "secrets/env.env"
        env         = true
        data        = <<EOH
{{- with nomadVar "secrets/phaseflow" -}}CRON_SECRET="{{ .cron_secret }}"{{- end -}}
EOH
      }
    }
  }
}
