#!/bin/bash

echo "🚀 Setting up local development environment for Prmbr..."

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first."
    echo "💡 Visit: https://docs.docker.com/get-docker/"
    exit 1
fi

# Check if Docker Compose is available
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo "❌ Docker Compose is not available. Please install Docker Compose."
    exit 1
fi

echo "🐳 Starting PostgreSQL database..."

# Start PostgreSQL with Docker Compose
if command -v docker-compose &> /dev/null; then
    docker-compose up -d postgres
else
    docker compose up -d postgres
fi

# Wait for database to be ready
echo "⏳ Waiting for database to be ready..."
sleep 10

# Test database connection
echo "🔍 Testing database connection..."
if node scripts/test-db-connection.js; then
    echo "✅ Database connection successful!"
else
    echo "⚠️  Database not ready yet, pushing schema..."
    
    # Generate Prisma client
    echo "📦 Generating Prisma client..."
    npx prisma generate
    
    # Push schema to database
    echo "🗄️  Pushing schema to database..."
    npx prisma db push --accept-data-loss
    
    # Test connection again
    echo "🔍 Testing database connection again..."
    if node scripts/test-db-connection.js; then
        echo "✅ Database setup complete!"
    else
        echo "❌ Database setup failed. Please check the logs."
        exit 1
    fi
fi

echo ""
echo "🎉 Local development environment is ready!"
echo "💡 You can now run: npm run dev"
echo ""
echo "📊 To view your database, run: npm run db:studio"
echo "🛑 To stop the database, run: docker-compose down"
