#!/bin/bash
set -e

echo "🚀 Starting Goa-GEL Backend Initialization..."

# Function to check if this is first boot
is_first_boot() {
  if [ ! -f "/app/data/.initialized" ]; then
    return 0  # true
  else
    return 1  # false
  fi
}

# Ensure data directory exists
mkdir -p /app/data

# Ensure .env file exists
touch /app/.env

# 1. Wait for and initialize database
echo "📊 Step 1: Database initialization..."
chmod +x /app/scripts/init-db.sh
/app/scripts/init-db.sh

# 2. Initialize blockchain (only on first boot or if not configured)
if is_first_boot || [ -z "$CONTRACT_ADDRESS_LICENSE_NFT" ] || [ "$CONTRACT_ADDRESS_LICENSE_NFT" = "0x0000000000000000000000000000000000000000" ]; then
  echo "🔗 Step 2: Blockchain initialization..."
  node /app/scripts/init-blockchain.js

  # Mark as initialized
  touch /app/data/.initialized
  echo "✅ Blockchain initialization complete!"

  # Reload environment variables
  if [ -f "/app/.env" ]; then
    export $(grep -v '^#' /app/.env | xargs)
  fi
else
  echo "⏭️  Step 2: Blockchain already initialized"
fi

# 3. Start the application
echo "🎯 Step 3: Starting NestJS application..."
exec npm run start:prod
