#!/bin/bash
# Complete setup script - run this after database is configured

cd /home/intlc/projects/Sankofa/api

echo "=========================================="
echo "Sovereign Stack Complete Setup"
echo "=========================================="
echo ""

# Check database connection first
DB_PASS=$(grep "^DB_PASSWORD=" .env 2>/dev/null | cut -d'=' -f2- | tr -d '"' | tr -d "'" | xargs)

if [ -z "$DB_PASS" ] || [ "$DB_PASS" = "your_secure_password_here" ]; then
  echo "❌ DB_PASSWORD not set in .env"
  echo ""
  echo "Please run first:"
  echo "  ./scripts/manual-db-setup.sh"
  exit 1
fi

# Test connection
if ! PGPASSWORD="$DB_PASS" psql -h localhost -U postgres -d sankofa -c "SELECT 1;" >/dev/null 2>&1; then
  echo "❌ Cannot connect to database"
  echo ""
  echo "Please:"
  echo "  1. Verify database exists: psql -U postgres -l | grep sankofa"
  echo "  2. Verify password is correct in .env"
  echo "  3. Run: ./scripts/manual-db-setup.sh"
  exit 1
fi

echo "✅ Database connection verified"
echo ""

# Run migrations
echo "Step 1: Running migrations..."
pnpm db:migrate:up && echo "✅ Migrations completed" || {
  echo "❌ Migration failed"
  exit 1
}

echo ""

# Seed services
echo "Step 2: Seeding services..."
pnpm db:seed:sovereign-stack && echo "✅ Services seeded" || {
  echo "❌ Seeding failed"
  exit 1
}

echo ""

# Verify
echo "Step 3: Verifying..."
pnpm verify:sovereign-stack && {
  echo ""
  echo "=========================================="
  echo "✅ SETUP COMPLETE!"
  echo "=========================================="
  echo ""
  echo "All 9 Sovereign Stack services are now registered!"
  echo "Access them via GraphQL API or marketplace portal."
} || {
  echo "⚠ Verification found issues"
  exit 1
}
