#!/bin/bash

# ProjectHub Quick Setup Script
# This script ensures proper configuration and deployment

set -e

echo "🚀 ProjectHub Setup Script"
echo "========================="

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

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

# Check if .env file exists
if [ ! -f .env ]; then
    echo "📝 Creating .env file with secure defaults..."
    cat > .env << EOF
# Generated by ProjectHub setup script on $(date)
JWT_SECRET=$(openssl rand -base64 32)
POSTGRES_PASSWORD=projecthub123
BACKEND_PORT=3009
FRONTEND_PORT=5174
POSTGRES_PORT=5433
CORS_ORIGIN=*
EOF
    echo "✅ .env file created"
else
    echo "📋 Using existing .env file"
fi

# Check if JWT_SECRET is set in .env
if ! grep -q "JWT_SECRET=" .env; then
    echo "⚠️  Warning: JWT_SECRET not found in .env file"
    echo "Adding JWT_SECRET..."
    echo "JWT_SECRET=$(openssl rand -base64 32)" >> .env
fi

# Check if required ports are available
check_port() {
    local port=$1
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        echo "⚠️  Warning: Port $port is already in use"
        return 1
    fi
    return 0
}

echo ""
echo "🔍 Checking port availability..."
PORT_ISSUES=0
check_port 3009 || PORT_ISSUES=$((PORT_ISSUES + 1))
check_port 5174 || PORT_ISSUES=$((PORT_ISSUES + 1))
check_port 5433 || PORT_ISSUES=$((PORT_ISSUES + 1))

if [ $PORT_ISSUES -gt 0 ]; then
    echo "⚠️  Some ports are in use. You may need to:"
    echo "   1. Stop conflicting services, or"
    echo "   2. Change ports in .env file"
    echo ""
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Pull latest images
echo ""
echo "📦 Pulling latest images..."
docker pull anubissbe/projecthub:latest
docker pull anubissbe/projecthub-frontend:latest

# Start services
echo ""
echo "🐳 Starting services..."
docker-compose down 2>/dev/null || true
docker-compose up -d

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

# Check if PostgreSQL is ready
echo ""
echo "🗄️  Checking database..."
RETRIES=30
until docker exec projecthub-postgres pg_isready -U projecthub >/dev/null 2>&1 || [ $RETRIES -eq 0 ]; do
    echo "   Waiting for PostgreSQL to be ready... ($RETRIES retries left)"
    sleep 2
    RETRIES=$((RETRIES - 1))
done

if [ $RETRIES -eq 0 ]; then
    echo "❌ PostgreSQL failed to start. Check logs with: docker logs projecthub-postgres"
    exit 1
fi

# Update admin password
echo ""
echo "🔐 Setting admin password..."
docker exec projecthub-postgres psql -U projecthub -d projecthub -c \
    "UPDATE users SET password = '\$2a\$10\$ILQeDcYjXZBPJDIAiA.PnOgs1rqZaYecV5dVLmjKdoFViZGX1W1.W' WHERE email = 'admin@projecthub.com';" >/dev/null 2>&1

# Health check
echo ""
echo "🏥 Running health checks..."

# Check backend
if curl -s http://localhost:3009/health | grep -q "healthy"; then
    echo "✅ Backend is healthy"
else
    echo "❌ Backend health check failed"
fi

# Test authentication
echo ""
echo "🔑 Testing authentication..."
AUTH_RESPONSE=$(curl -s -X POST http://localhost:3009/api/auth/login \
    -H "Content-Type: application/json" \
    -d '{"email":"admin@projecthub.com","password":"admin123"}')

if echo "$AUTH_RESPONSE" | grep -q "token"; then
    echo "✅ Authentication successful"
else
    echo "❌ Authentication failed: $AUTH_RESPONSE"
fi

# Show status
echo ""
echo "📊 Service Status:"
docker-compose ps

echo ""
echo "✨ Setup complete!"
echo ""
echo "🌐 Access ProjectHub at:"
echo "   Frontend: http://localhost:5174"
echo "   API:      http://localhost:3009"
echo ""
echo "📧 Login credentials:"
echo "   Email:    admin@projecthub.com"
echo "   Password: admin123"
echo ""
echo "📖 For troubleshooting, see TROUBLESHOOTING.md"
echo "📝 To view logs: docker-compose logs -f"