#!/bin/sh
set -e

echo "=== OpenCRM Startup ==="

# Wait for database to be ready
echo "Waiting for database connection..."
MAX_RETRIES=30
RETRY_COUNT=0

while ! nc -z db 3306 2>/dev/null; do
    RETRY_COUNT=$((RETRY_COUNT + 1))
    if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then
        echo "Error: Database not available after $MAX_RETRIES attempts"
        exit 1
    fi
    echo "  Attempt $RETRY_COUNT/$MAX_RETRIES - waiting..."
    sleep 2
done
echo "Database is ready!"

# Run migrations
echo "Running database migrations..."
npx prisma migrate deploy

# Seed database if RUN_SEED is set (first install)
if [ "$RUN_SEED" = "true" ]; then
    echo "Seeding database..."
    npx tsx prisma/seed.ts
fi

# Einmal-Bereinigung für Pentest-Reste (Runde 12): XSS-Strings aus
# Customer/User-Feldern entfernen + unbekannte AppSettings löschen.
# Idempotent – läuft bei jedem Container-Start ohne Risiko.
echo "Running data cleanup..."
npx tsx prisma/cleanup-xss-and-mass-assignment.ts || echo "  (Cleanup übersprungen, nicht-kritisch)"

# Start the application
echo "Starting OpenCRM server..."
exec node dist/index.js
