#!/bin/bash
# Generiert realistische HACCP-Testdaten für die letzten 30 Tage

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=... ./seed-testdata.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')

echo "✓ Eingeloggt"

TENANT_ID="mengbzc3ajxpccz"

# Stationen als JSON laden
STATIONS_JSON=$(curl -sf "$PB_URL/api/collections/stations/records?filter=tenant%3D'$TENANT_ID'&perPage=50" \
  -H "Authorization: $TOKEN")

STATION_COUNT=$(echo "$STATIONS_JSON" | jq '.items | length')
echo "→ $STATION_COUNT Stationen gefunden"

NAMES=("Maria S." "Klaus B." "Sandra M." "Tobias R." "Anna K." "Michael F." "Lisa W.")
NOTES_ABW=("Tür stand leicht offen" "Dichtung prüfen" "Kompressor läuft laut" "Temperatur leicht erhöht" "Nach Lieferung noch warm")
NOTES_KRIT=("Tür war 2h offen" "Kompressor ausgefallen" "Sofortmaßnahme eingeleitet" "Produkte aussortiert" "Techniker verständigt")

create_log() {
  local station_id=$1
  local date_str=$2
  local status=$3
  local temp=$4
  local notes=$5
  local person=$6

  curl -sf -X POST "$PB_URL/api/collections/check_logs/records" \
    -H "Authorization: $TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
      \"station\":    \"$station_id\",
      \"tenant\":     \"$TENANT_ID\",
      \"temperature\": $temp,
      \"status\":     \"$status\",
      \"notes\":      \"$notes\",
      \"checked_by\": \"$person\",
      \"created\":    \"$date_str\",
      \"updated\":    \"$date_str\"
    }" > /dev/null
}

rand_between() {
  local min=$1
  local max=$2
  echo $(( min + RANDOM % (max - min + 1) ))
}

echo "→ Erstelle Einträge für die letzten 30 Tage..."
COUNT=0

for DAY in $(seq 29 -1 0); do
  # Datum berechnen (macOS + Linux kompatibel)
  if date -v -${DAY}d +"%Y-%m-%d" > /dev/null 2>&1; then
    DATE=$(date -v -${DAY}d +"%Y-%m-%d")
    DOW=$(date -v -${DAY}d +"%u")
  else
    DATE=$(date -d "-${DAY} days" +"%Y-%m-%d")
    DOW=$(date -d "-${DAY} days" +"%u")
  fi

  for i in $(seq 0 $((STATION_COUNT - 1))); do
    SID=$(echo "$STATIONS_JSON"  | jq -r ".items[$i].id")
    TYPE=$(echo "$STATIONS_JSON" | jq -r ".items[$i].type")
    TMIN=$(echo "$STATIONS_JSON" | jq -r ".items[$i].target_temp_min // 0")
    TMAX=$(echo "$STATIONS_JSON" | jq -r ".items[$i].target_temp_max // 0")

    PERSON=${NAMES[$((RANDOM % ${#NAMES[@]}))]}

    if [ "$TYPE" = "kuehlschrank" ] || [ "$TYPE" = "tiefkuehl" ]; then
      # Morgencheck
      HOUR=$(rand_between 7 8)
      MIN_T=$(rand_between 0 5)
      SEC_T=$(rand_between 0 59)
      TIME="${DATE} 0${HOUR}:$(printf "%02d" $MIN_T):$(printf "%02d" $SEC_T)"

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

      # Abendcheck (Mo-Fr)
      if [ "$DOW" -lt 6 ]; then
        HOUR=$(rand_between 17 19)
        TIME="${DATE} ${HOUR}:$(printf "%02d" $(rand_between 0 59)):00"
        TEMP=$(rand_between $TMIN $TMAX)
        create_log "$SID" "$TIME" "ok" "$TEMP" "" "$PERSON"
        COUNT=$((COUNT + 1))
      fi

    elif [ "$TYPE" = "warmhalte" ]; then
      TIME="${DATE} 11:$(printf "%02d" $(rand_between 0 30)):00"
      RAND=$((RANDOM % 100))
      if [ $RAND -lt 85 ]; then
        TEMP=$(rand_between $TMIN $TMAX)
        create_log "$SID" "$TIME" "ok" "$TEMP" "" "$PERSON"
      else
        TEMP=$(( TMIN - 3 - RANDOM % 5 ))
        NOTE=${NOTES_ABW[$((RANDOM % ${#NOTES_ABW[@]}))]}
        create_log "$SID" "$TIME" "abweichung" "$TEMP" "$NOTE" "$PERSON"
      fi
      COUNT=$((COUNT + 1))

    elif [ "$TYPE" = "hygiene" ]; then
      if [ "$DOW" -eq 1 ]; then
        TIME="${DATE} 09:$(printf "%02d" $(rand_between 0 30)):00"
        create_log "$SID" "$TIME" "ok" "0" "" "$PERSON"
        COUNT=$((COUNT + 1))
      fi
    fi
  done

  printf "  Tag -%02d: %s (%s)..." "$DAY" "$DATE" "DOW $DOW"
  echo " OK"
done

echo ""
echo "  ✓ $COUNT Einträge erstellt"
