#!/bin/bash

# cPanel Deployment Script
# Run this script on your cPanel server after uploading files

echo "🚀 Starting CRM Deployment on cPanel..."

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    echo "❌ Error: package.json not found. Are you in the correct directory?"
    exit 1
fi

# Check Node.js version
echo "📋 Checking Node.js version..."
NODE_VERSION=$(node --version)
echo "Node.js version: $NODE_VERSION"

# Install dependencies
echo "📦 Installing dependencies..."
npm install --production

# Generate Prisma client
echo "🔨 Generating Prisma client..."
npx prisma generate

# Check if .env.production exists
if [ ! -f ".env.production" ]; then
    echo "⚠️  Warning: .env.production not found. Creating from template..."
    cp env.production.example .env.production
    echo "❗ Please update .env.production with your actual values before continuing"
    exit 1
fi

# Test database connection
echo "🔌 Testing database connection..."
node -e "
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
prisma.\$connect()
    .then(() => {
        console.log('✅ Database connection successful');
        return prisma.\$disconnect();
    })
    .catch((error) => {
        console.error('❌ Database connection failed:', error.message);
        process.exit(1);
    });
"

# Try to build the application
echo "🏗️  Attempting to build application..."
if npm run build; then
    echo "✅ Build successful"
else
    echo "⚠️  Build failed. You can still run in development mode"
    echo "   Use: NODE_ENV=development npm start"
fi

# Run production setup script
echo "⚙️  Running production setup..."
if [ -f "scripts/production-setup.js" ]; then
    node scripts/production-setup.js
else
    echo "⚠️  Production setup script not found"
fi

echo "✅ Deployment process completed!"
echo ""
echo "📝 Next steps:"
echo "1. Update .env.production with your actual database credentials"
echo "2. Set up Node.js app in cPanel with startup file: server.js"
echo "3. Configure SSL certificate"
echo "4. Test your application"
echo ""
echo "🌍 Your app should be accessible at: https://yourdomain.com" 