#!/bin/bash
# Löscht heutige Demo-Einträge und erstellt frische für die letzte Stunde.
# Cron: jede Stunde via DSM Task Scheduler oder crontab

set -euo pipefail
PB_URL="${PB_URL:-https://api.checkflo.de}"

if [ -z "${PB_EMAIL:-}" ] || [ -z "${PB_PASSWORD:-}" ]; then
  echo "Aufruf: PB_EMAIL=... PB_PASSWORD=... ./demo-refresh.sh"; exit 1
fi

TOKEN=$(curl -sf -X POST "$PB_URL/api/collections/_superusers/auth-with-password" \
  -H "Content-Type: application/json" \
  -d "{\"identity\":\"$PB_EMAIL\",\"password\":\"$PB_PASSWORD\"}" | jq -r '.token')

TENANT_ID="mengbzc3ajxpccz"
NOW=$(date +"%Y-%m-%d %H:00:00")
TODAY=$(date +"%Y-%m-%d")

# Alle heutigen Demo-Einträge löschen
EXISTING=$(curl -sf \
  "$PB_URL/api/collections/check_logs/records?filter=tenant%3D'$TENANT_ID'%26%26created%3E%3D'$TODAY%2000%3A00%3A00'&perPage=200" \
  -H "Authorization: $TOKEN" | jq -r '.items[].id')

COUNT_DEL=0
for id in $EXISTING; do
  curl -sf -X DELETE "$PB_URL/api/collections/check_logs/records/$id" \
    -H "Authorization: $TOKEN" > /dev/null
  COUNT_DEL=$((COUNT_DEL + 1))
done
echo "→ $COUNT_DEL alte Einträge gelöscht"

# Stationen laden
STATIONS=$(curl -sf "$PB_URL/api/collections/stations/records?filter=tenant%3D'$TENANT_ID'%26%26active%3Dtrue&perPage=50" \
  -H "Authorization: $TOKEN")
STATION_COUNT=$(echo "$STATIONS" | jq '.items | length')

NAMES=("Maria S." "Klaus B." "Sandra M." "Tobias R." "Anna K." "Michael F.")
NOTES_ABW=("Tür stand leicht offen" "Dichtung prüfen" "Temperatur leicht erhöht")
NOTES_KRIT=("Tür war 2h offen" "Kompressor ausgefallen" "Sofortmaßnahme eingeleitet")

rand_between() { echo $(( $1 + RANDOM % ($2 - $1 + 1) )); }

create_log() {
  curl -sf -X POST "$PB_URL/api/collections/check_logs/records" \
    -H "Authorization: $TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
      \"station\":    \"$1\",
      \"tenant\":     \"$TENANT_ID\",
      \"temperature\": $2,
      \"status\":     \"$3\",
      \"notes\":      \"$4\",
      \"checked_by\": \"$5\",
      \"created\":    \"$6\",
      \"updated\":    \"$6\"
    }" > /dev/null
}

# Für jede vergangene Stunde seit 7:00 Einträge erstellen
CURRENT_HOUR=$(date +"%H")
COUNT_NEW=0

for HOUR in $(seq 7 $CURRENT_HOUR); do
  for i in $(seq 0 $((STATION_COUNT - 1))); do
    SID=$(echo "$STATIONS"  | jq -r ".items[$i].id")
    TYPE=$(echo "$STATIONS" | jq -r ".items[$i].type")
    TMIN=$(echo "$STATIONS" | jq -r ".items[$i].target_temp_min // 0")
    TMAX=$(echo "$STATIONS" | jq -r ".items[$i].target_temp_max // 0")
    PERSON=${NAMES[$((RANDOM % ${#NAMES[@]}))]}
    MIN=$(rand_between 0 59)
    TIME="$TODAY $(printf "%02d" $HOUR):$(printf "%02d" $MIN):00"

    if [ "$TYPE" = "hygiene" ] && [ "$HOUR" != "9" ]; then continue; fi

    RAND=$((RANDOM % 100))
    if [ $RAND -lt 88 ]; then
      TEMP=$(rand_between $TMIN $TMAX)
      create_log "$SID" "$TEMP" "ok" "" "$PERSON" "$TIME"
    elif [ $RAND -lt 96 ]; then
      TEMP=$((TMAX + 1 + RANDOM % 3))
      NOTE=${NOTES_ABW[$((RANDOM % ${#NOTES_ABW[@]}))]}
      create_log "$SID" "$TEMP" "abweichung" "$NOTE" "$PERSON" "$TIME"
    else
      TEMP=$((TMAX + 4 + RANDOM % 4))
      NOTE=${NOTES_KRIT[$((RANDOM % ${#NOTES_KRIT[@]}))]}
      create_log "$SID" "$TEMP" "kritisch" "$NOTE" "$PERSON" "$TIME"
    fi
    COUNT_NEW=$((COUNT_NEW + 1))
  done
done

echo "✓ $COUNT_NEW neue Demo-Einträge erstellt (bis $(printf "%02d" $CURRENT_HOUR):00 Uhr)"
