#!/bin/bash

echo "🔧 Configuring Database Connection"
echo "================================="

# Create .env file with your credentials
cat > .env << EOF
# Server Configuration
PORT=3000
NODE_ENV=development

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_NAME=dubai_dld
DB_USER=root
DB_PASSWORD=Admin@123

# NLP Configuration
NLP_LIBRARY=natural

# API Configuration
API_KEY=your_api_key_here
RATE_LIMIT=100
EOF

echo "✅ Created .env file with your database credentials"

# Test database connection
echo "🔍 Testing database connection..."
mysql -h localhost -u root -pAdmin@123 -e "SELECT 1;" 2>/dev/null

if [ $? -eq 0 ]; then
    echo "✅ Database connection successful"
    
    # Check if database exists
    echo "🔍 Checking if dubai_dld database exists..."
    DB_EXISTS=$(mysql -h localhost -u root -pAdmin@123 -e "SHOW DATABASES LIKE 'dubai_dld';" 2>/dev/null | grep dubai_dld)
    
    if [ -z "$DB_EXISTS" ]; then
        echo "⚠️  Database 'dubai_dld' does not exist. Creating it..."
        mysql -h localhost -u root -pAdmin@123 -e "CREATE DATABASE dubai_dld CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null
        
        if [ -f "2.sql" ]; then
            echo "📊 Importing database schema..."
            mysql -h localhost -u root -pAdmin@123 dubai_dld < 2.sql
            echo "✅ Database schema imported successfully"
        else
            echo "⚠️  SQL file (2.sql) not found. Please ensure it's in the project root."
        fi
    else
        echo "✅ Database 'dubai_dld' already exists"
    fi
    
    # Test tables
    echo "🔍 Checking tables..."
    TABLE_COUNT=$(mysql -h localhost -u root -pAdmin@123 dubai_dld -e "SHOW TABLES;" 2>/dev/null | wc -l)
    echo "📊 Found $TABLE_COUNT tables in dubai_dld database"
    
else
    echo "❌ Database connection failed. Please check your credentials."
    echo "   Host: localhost"
    echo "   Port: 3306"
    echo "   Username: root"
    echo "   Password: Admin@123"
    exit 1
fi

echo ""
echo "🎉 Database configuration complete!"
echo ""
echo "Next steps:"
echo "1. Install dependencies: npm install"
echo "2. Start the server: npm run dev"
echo "3. Test the API: curl http://localhost:3000/health"
echo "4. Open public/index.html for the demo dashboard"

