#!/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
if [ $? -ne 0 ]; then
  echo "❌ Database migrations failed. Aborting startup."
  exit 1
fi

# ─── 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: Seed SymbolTemplates (idempotent) ───
echo "[2b/3] Seeding symbol templates..."
node -e "
const { PrismaClient } = require('@prisma/client');
const fs = require('fs');
const path = require('path');
const prisma = new PrismaClient();

async function seedTemplates() {
  const sigDir = path.join(process.cwd(), 'public', 'signaturen');
  let files = [];
  try { files = fs.readdirSync(sigDir).filter(f => f.endsWith('.svg')).sort(); } catch(e) { console.log('No signaturen dir'); }
  let created = 0, skipped = 0;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const displayName = file.replace(/\.svg$/i, '').replace(/[_-]/g, ' ').trim();
    const fileKey = 'signaturen/' + file;
    const existing = await prisma.symbolTemplate.findFirst({ where: { svgPath: fileKey } }).catch(() => null);
    if (existing) { skipped++; continue; }
    await prisma.symbolTemplate.create({
      data: {
        packageId: 'feuerwehr-ch',
        packageName: 'Feuerwehr Schweiz',
        categoryName: 'Sonstiges',
        name: displayName,
        svgPath: fileKey,
        tags: [displayName.toLowerCase()],
        sortOrder: i,
      }
    }).catch(() => {});
    created++;
  }
  console.log('Templates: ' + created + ' created, ' + skipped + ' skipped');
  await prisma.\$disconnect();
}
seedTemplates().catch(() => { console.log('Template seed skipped'); prisma.\$disconnect(); });
" || echo "  Warning: template seed failed"

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