#!/bin/sh
set -e

echo "=== VIP Coordinator Backend - Starting ==="

# Function to wait for PostgreSQL to be ready
wait_for_postgres() {
  echo "Waiting for PostgreSQL to be ready..."

  # Extract host and port from DATABASE_URL
  # Format: postgresql://user:pass@host:port/dbname
  DB_HOST=$(echo $DATABASE_URL | sed -n 's/.*@\(.*\):.*/\1/p')
  DB_PORT=$(echo $DATABASE_URL | sed -n 's/.*:\([0-9]*\)\/.*/\1/p')

  # Default to standard PostgreSQL port if not found
  DB_PORT=${DB_PORT:-5432}

  echo "Checking PostgreSQL at ${DB_HOST}:${DB_PORT}..."

  # Wait up to 60 seconds for PostgreSQL
  timeout=60
  counter=0

  until nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null; do
    counter=$((counter + 1))
    if [ $counter -gt $timeout ]; then
      echo "ERROR: PostgreSQL not available after ${timeout} seconds"
      exit 1
    fi
    echo "PostgreSQL not ready yet... waiting (${counter}/${timeout})"
    sleep 1
  done

  echo "✓ PostgreSQL is ready!"
}

# Function to run database migrations
run_migrations() {
  echo "Running database migrations..."

  if npx prisma migrate deploy; then
    echo "✓ Migrations completed successfully!"
  else
    echo "ERROR: Migration failed!"
    exit 1
  fi
}

# Function to seed database (optional)
seed_database() {
  if [ "$RUN_SEED" = "true" ]; then
    echo "Seeding database..."

    if npx prisma db seed; then
      echo "✓ Database seeded successfully!"
    else
      echo "WARNING: Database seeding failed (continuing anyway)"
    fi
  else
    echo "Skipping database seeding (RUN_SEED not set to 'true')"
  fi
}

# Main execution
main() {
  # Wait for database to be available
  wait_for_postgres

  # Run migrations
  run_migrations

  # Optionally seed database
  seed_database

  echo "=== Starting NestJS Application ==="
  echo "Node version: $(node --version)"
  echo "Environment: ${NODE_ENV:-production}"
  echo "Starting server on port 3000..."

  # Start the application
  exec node dist/src/main
}

# Run main function
main
