#!/bin/bash

set -e

echo "🚀 Initializing GoodGo Microservices Project..."

# EN: Check prerequisites
# VI: Kiểm tra các điều kiện tiên quyết
if ! command -v pnpm &> /dev/null; then
    echo "❌ PNPM is not installed. Please install it first: npm install -g pnpm"
    exit 1
fi

if ! command -v docker &> /dev/null; then
    echo "⚠️  Docker is not installed. Some features may not work."
fi

# EN: Install dependencies
# VI: Cài đặt các gói phụ thuộc
echo "📦 Installing dependencies..."
pnpm install

# EN: Generate Prisma clients
# VI: Tạo Prisma generic clients
echo "🔧 Generating Prisma clients..."
cd services/iam-service
pnpm prisma:generate || echo "⚠️  Prisma generation skipped (database not available)"
cd ../..

# EN: Setup environment files
# VI: Thiết lập các file biến môi trường
echo "📝 Setting up environment files..."
if [ ! -f "services/iam-service/.env" ]; then
    cp services/iam-service/env.local.example services/iam-service/.env.local 2>/dev/null || echo "⚠️  IAM service .env file not found"
fi

if [ ! -f "deployments/local/.env.local" ]; then
    cp deployments/local/env.local.example deployments/local/.env.local
    echo "✅ Created deployments/local/.env.local"
    echo "⚠️  IMPORTANT: Edit .env.local and add your Neon DATABASE_URL"
fi

if [ ! -f "apps/web-admin/.env.local" ]; then
    cp apps/web-admin/.env.example apps/web-admin/.env.local 2>/dev/null || echo "⚠️  Web admin .env.example not found"
fi

if [ ! -f "apps/web-client/.env.local" ]; then
    cp apps/web-client/.env.example apps/web-client/.env.local 2>/dev/null || echo "⚠️  Web client .env.example not found"
fi

echo "✅ Project initialization complete!"
echo ""
echo "Next steps:"
echo "1. Setup Neon database: ./scripts/db/setup-neon.sh"
echo "2. Update .env files with your Neon DATABASE_URL"
echo "3. Start all services: ./scripts/dev/start-all.sh"
echo "4. Run migrations: ./scripts/db/migrate.sh iam-service dev"
echo "5. Seed database: ./scripts/db/seed.sh iam-service"
echo "6. Start services: pnpm dev"
echo ""
echo "📚 See infra/databases/neon/README.md for Neon setup details"
