#!/bin/bash

# Development Environment Setup Script
# This script sets up the development environment for Sankofa Phoenix

set -e

echo "🔥 Setting up Sankofa Phoenix development environment..."

# Check prerequisites
echo "Checking prerequisites..."
command -v node >/dev/null 2>&1 || { echo "Node.js is required but not installed. Aborting." >&2; exit 1; }
command -v pnpm >/dev/null 2>&1 || { echo "pnpm is required but not installed. Aborting." >&2; exit 1; }

# Install root dependencies
echo "Installing root dependencies..."
pnpm install

# Install API dependencies
echo "Installing API dependencies..."
cd api
if [ -f "package.json" ]; then
  npm install || pnpm install
fi
cd ..

# Install Portal dependencies
echo "Installing Portal dependencies..."
cd portal
if [ -f "package.json" ]; then
  npm install
fi
cd ..

# Create .env.local files if they don't exist
echo "Setting up environment files..."

if [ ! -f ".env.local" ]; then
  cat > .env.local << EOF
NEXT_PUBLIC_GRAPHQL_ENDPOINT=http://localhost:4000/graphql
NEXT_PUBLIC_APP_URL=http://localhost:3000
NODE_ENV=development
EOF
  echo "Created .env.local"
fi

if [ ! -f "api/.env.local" ]; then
  cat > api/.env.local << EOF
DB_HOST=localhost
DB_PORT=5432
DB_NAME=sankofa
DB_USER=postgres
DB_PASSWORD=postgres
JWT_SECRET=dev-secret-change-in-production
NODE_ENV=development
PORT=4000
EOF
  echo "Created api/.env.local"
fi

# Setup database (if PostgreSQL is available)
if command -v psql >/dev/null 2>&1; then
  echo "Setting up database..."
  createdb sankofa 2>/dev/null || echo "Database 'sankofa' may already exist or PostgreSQL not running"
  
  if [ -f "api/src/db/migrate.ts" ]; then
    echo "Running database migrations..."
    cd api
    npm run db:migrate up || pnpm db:migrate up || echo "Migrations may have already run"
    cd ..
  fi
else
  echo "PostgreSQL not found. Skipping database setup."
  echo "You can set up PostgreSQL later or use Docker: docker-compose up postgres"
fi

echo ""
echo "✅ Development environment setup complete!"
echo ""
echo "Next steps:"
echo "  1. Start PostgreSQL: docker-compose up -d postgres (or use your own instance)"
echo "  2. Start API: cd api && pnpm dev"
echo "  3. Start Frontend: pnpm dev"
echo "  4. Start Portal: cd portal && npm run dev"
echo ""

