#!/bin/bash

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo "🚀 Initializing GoodGo Microservices Project..."
echo ""

# EN: Check prerequisites
# VI: Kiểm tra các điều kiện tiên quyết

# Check Node.js version
if ! command -v node &> /dev/null; then
    echo -e "${RED}❌ Node.js is not installed. Please install Node.js v20.0.0 or higher${NC}"
    exit 1
fi

NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 20 ]; then
    echo -e "${RED}❌ Node.js version is too old. Required: v20.0.0+, Current: $(node -v)${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Node.js $(node -v) detected${NC}"

# Check PNPM
if ! command -v pnpm &> /dev/null; then
    echo -e "${RED}❌ PNPM is not installed. Please install it first:${NC}"
    echo "   npm install -g pnpm"
    exit 1
fi

PNPM_VERSION=$(pnpm -v)
echo -e "${GREEN}✓ PNPM v${PNPM_VERSION} detected${NC}"

# Check Docker
if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}⚠️  Docker is not installed. Local infrastructure features will not work.${NC}"
    echo -e "${YELLOW}   Please install Docker Desktop: https://www.docker.com/products/docker-desktop${NC}"
else
    DOCKER_VERSION=$(docker -v | cut -d' ' -f3 | cut -d',' -f1)
    echo -e "${GREEN}✓ Docker ${DOCKER_VERSION} detected${NC}"
fi

echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# EN: Install dependencies
# VI: Cài đặt các gói phụ thuộc
echo -e "${BLUE}📦 Installing dependencies...${NC}"
pnpm install
echo -e "${GREEN}✓ Dependencies installed${NC}"
echo ""

# EN: Setup environment files
# VI: Thiết lập các file biến môi trường
echo -e "${BLUE}📝 Setting up environment files...${NC}"

# Function to copy env file
copy_env_file() {
    local source=$1
    local target=$2
    local description=$3
    
    if [ -f "$source" ]; then
        if [ ! -f "$target" ]; then
            cp "$source" "$target"
            echo -e "${GREEN}✓ Created ${target}${NC}"
            if [ -n "$description" ]; then
                echo -e "${YELLOW}  ⚠️  ${description}${NC}"
            fi
        else
            echo -e "${BLUE}→ ${target} already exists (skipped)${NC}"
        fi
    else
        echo -e "${YELLOW}⚠️  ${source} not found (skipped)${NC}"
    fi
}

# Copy env files
copy_env_file "deployments/local/env.local.example" "deployments/local/.env.local" "IMPORTANT: Edit .env.local and add your Neon DATABASE_URL"
copy_env_file "services/iam-service/env.local.example" "services/iam-service/.env.local" ""
copy_env_file "apps/web-client/.env.local" "apps/web-client/.env.local.backup" "" 2>/dev/null || true

echo ""

# EN: Generate Prisma clients
# VI: Tạo Prisma clients
echo -e "${BLUE}🔧 Generating Prisma clients...${NC}"
if [ -d "services/iam-service" ]; then
    cd services/iam-service
    if pnpm prisma generate 2>/dev/null; then
        echo -e "${GREEN}✓ Prisma client generated for iam-service${NC}"
    else
        echo -e "${YELLOW}⚠️  Prisma generation skipped (database schema may need setup)${NC}"
    fi
    cd ../..
fi
echo ""

# EN: Check for additional setup needed
# VI: Kiểm tra các thiết lập bổ sung cần thiết
echo -e "${BLUE}🔍 Checking additional setup requirements...${NC}"

if [ ! -f "deployments/local/.env.local" ] || ! grep -q "DATABASE_URL=" deployments/local/.env.local 2>/dev/null; then
    echo -e "${YELLOW}⚠️  Neon database not configured${NC}"
fi

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}✅ Project initialization complete!${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "${BLUE}📋 Next steps:${NC}"
echo ""
echo "  1. 🗄️  Setup Neon database:"
echo "     ./scripts/db/setup-neon.sh"
echo ""
echo "  2. ⚙️  Update environment variables:"
echo "     Edit deployments/local/.env.local and add your DATABASE_URL"
echo ""
echo "  3. 🔄 Run database migrations:"
echo "     pnpm --filter @goodgo/iam-service prisma migrate dev"
echo ""
echo "  4. 🌱 Seed database (optional):"
echo "     ./scripts/db/seed.sh iam-service"
echo ""
echo "  5. 🐳 Start local infrastructure:"
echo "     cd deployments/local && docker-compose up -d"
echo ""
echo "  6. 🚀 Start development servers:"
echo "     pnpm dev"
echo ""
echo -e "${BLUE}📚 Documentation:${NC}"
echo "   • Neon setup: docs/vi/guides/neon-database.md"
echo "   • Getting started: docs/vi/guides/getting-started.md"
echo "   • Development: docs/vi/guides/development.md"
echo ""
