#!/bin/sh
set -e

echo "=== Lageplan Startup ==="

# ─── Step 1: Run migrations (uses PrismaClient raw SQL, no CLI needed) ───
echo "[1/3] Running database migrations..."
node prisma/migrate.js || echo "  Warning: migrations had issues (may be first run)"

# ─── Step 2: Conditional seeding ───
echo "[2/3] Checking if seeding is needed..."
TENANT_COUNT=$(node -e "
  const { PrismaClient } = require('@prisma/client');
  const p = new PrismaClient();
  p.tenant.count().then(c => { console.log(c); p.\$disconnect(); }).catch(() => { console.log('0'); p.\$disconnect(); });
" 2>/dev/null || echo "0")

if [ "$TENANT_COUNT" = "0" ] || [ -z "$TENANT_COUNT" ]; then
  echo "  Empty database — running full seed..."
  node prisma/seed.js || echo "  Warning: seed failed"
else
  echo "  $TENANT_COUNT tenant(s) found — skipping full seed"
  # Only refresh icons if count doesn't match expected 117 SVGs
  ICON_COUNT=$(node -e "
    const { PrismaClient } = require('@prisma/client');
    const p = new PrismaClient();
    p.iconAsset.count({ where: { isSystem: true, fileKey: { endsWith: '.svg' } } }).then(c => { console.log(c); p.\$disconnect(); }).catch(() => { console.log('0'); p.\$disconnect(); });
  " 2>/dev/null || echo "0")
  if [ "$ICON_COUNT" -lt 100 ] 2>/dev/null || [ "$ICON_COUNT" = "0" ] || [ -z "$ICON_COUNT" ]; then
    echo "  $ICON_COUNT SVG icons found (expected 117) — refreshing..."
    node prisma/seed-icons-only.js || echo "  Warning: icon seed failed"
  else
    echo "  $ICON_COUNT SVG icons present — skipping icon seed"
  fi
fi

# ─── Step 3: Start server ───
echo "[3/3] Starting server..."
exec node server-custom.js
