#!/bin/bash
# Legt Demo-Tenant "Schmidt Hygiene GmbH" mit blauer CI an

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-schmidt.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 anlegen
TENANT=$(curl -sf -X POST "$PB_URL/api/collections/tenants/records" \
  -H "Authorization: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name":          "Schmidt Hygiene GmbH",
    "slug":          "schmidt-hygiene",
    "primary_color": "#1B4FBF",
    "plan":          "pro",
    "active":        true
  }')
TENANT_ID=$(echo "$TENANT" | jq -r '.id')
echo "✓ Tenant: Schmidt Hygiene GmbH ($TENANT_ID)"

# Station anlegen (Kühltheke Metzgerei)
QR_ID=$(python3 -c "import uuid; print(str(uuid.uuid4()))" 2>/dev/null || cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen | tr '[:upper:]' '[:lower:]')

STATION=$(curl -sf -X POST "$PB_URL/api/collections/stations/records" \
  -H "Authorization: $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{
    \"tenant\":          \"$TENANT_ID\",
    \"name\":            \"Fleischkühltheke\",
    \"type\":            \"kuehlschrank\",
    \"target_temp_min\": 0,
    \"target_temp_max\": 4,
    \"qr_id\":           \"$QR_ID\",
    \"active\":          true
  }")
STATION_ID=$(echo "$STATION" | jq -r '.id')
echo "✓ Station: Fleischkühltheke ($QR_ID)"

echo ""
echo "  QR-Scan URL: https://checkflo.de/s/$QR_ID"
echo "  Tenant-ID:   $TENANT_ID"
echo ""
echo "  → Diese QR-URL in +page.svelte für den iPhone-Mockup eintragen"
