#!/bin/bash

# Token Aggregation Service Setup Script

set -e

echo "🚀 Setting up Token Aggregation Service..."

# Check Node.js version
echo "📦 Checking Node.js version..."
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 20 ]; then
  echo "❌ Node.js 20+ is required. Current version: $(node -v)"
  exit 1
fi
echo "✅ Node.js version: $(node -v)"

# Install dependencies
echo "📦 Installing dependencies..."
npm install

# Check if .env exists
if [ ! -f .env ]; then
  echo "📝 Creating .env file from .env.example..."
  cp .env.example .env
  echo "⚠️  Please edit .env file with your configuration"
else
  echo "✅ .env file exists"
fi

# Build the project
echo "🔨 Building TypeScript..."
npm run build

# Check database connection
echo "🔍 Checking database connection..."
if [ -z "$DATABASE_URL" ]; then
  echo "⚠️  DATABASE_URL not set. Please configure it in .env"
else
  echo "✅ DATABASE_URL is set"
fi

# Verify database migration
echo "📊 Verifying database migration..."
echo "⚠️  Please ensure migration 0011_token_aggregation_schema.up.sql has been run"
echo "   Location: explorer-monorepo/backend/database/migrations/0011_token_aggregation_schema.up.sql"

echo ""
echo "✅ Setup complete!"
echo ""
echo "Next steps:"
echo "1. Edit .env file with your configuration"
echo "2. Run database migration if not already done"
echo "3. Start the service: npm start"
echo "4. Or run in development: npm run dev"
