#!/bin/bash

##############################################
# Nandail Seba Backend - Automated Setup
# Run this script on your Ubuntu/Debian server
##############################################

set -e  # Exit on error

echo "🚀 Nandail Seba Backend - Automated Setup Starting..."
echo "======================================================"
echo ""

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

# Function to print colored output
print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_info() {
    echo -e "${YELLOW}ℹ️  $1${NC}"
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    print_error "Please run as root (use: sudo bash auto-setup.sh)"
    exit 1
fi

print_info "Step 1/10: System Update"
apt-get update -y
apt-get upgrade -y
print_success "System updated"

print_info "Step 2/10: Installing Node.js 18.x"
curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
apt-get install -y nodejs
node --version
npm --version
print_success "Node.js installed"

print_info "Step 3/10: Installing MySQL 8.0"
apt-get install -y mysql-server

# Start MySQL
systemctl start mysql
systemctl enable mysql
print_success "MySQL installed and started"

print_info "Step 4/10: Configuring MySQL"
# Generate random password
MYSQL_ROOT_PASSWORD=$(openssl rand -base64 12)
DB_PASSWORD=$(openssl rand -base64 12)

# Secure MySQL installation
mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$MYSQL_ROOT_PASSWORD';"
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "DELETE FROM mysql.user WHERE User='';"
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');"
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "DROP DATABASE IF EXISTS test;"
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';"
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "FLUSH PRIVILEGES;"

# Create database and user
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "CREATE DATABASE IF NOT EXISTS nandailseba_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "CREATE USER IF NOT EXISTS 'nandailseba_user'@'localhost' IDENTIFIED BY '$DB_PASSWORD';"
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "GRANT ALL PRIVILEGES ON nandailseba_db.* TO 'nandailseba_user'@'localhost';"
mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "FLUSH PRIVILEGES;"

print_success "MySQL configured"

print_info "Step 5/10: Installing PM2 (Process Manager)"
npm install -g pm2
print_success "PM2 installed"

print_info "Step 6/10: Installing Git"
apt-get install -y git
print_success "Git installed"

print_info "Step 7/10: Creating Application Directory"
APP_DIR="/var/www/nandailseba-backend"
mkdir -p $APP_DIR
cd $APP_DIR

# Check if backend files exist
if [ ! -f "package.json" ]; then
    print_info "Please upload your backend files to: $APP_DIR"
    print_info "You can use: scp -r ./backend/* root@your-server:$APP_DIR/"
    print_info "Or use Git to clone your repository"
    
    read -p "Press Enter after uploading files..."
fi

print_success "Application directory ready"

print_info "Step 8/10: Installing Backend Dependencies"
if [ -f "package.json" ]; then
    npm install --production
    print_success "Dependencies installed"
else
    print_error "package.json not found. Please upload backend files first."
    exit 1
fi

print_info "Step 9/10: Creating Environment File"

# Create .env file
cat > .env << EOF
# Server Configuration
NODE_ENV=production
PORT=3000
API_VERSION=v1

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_USER=nandailseba_user
DB_PASSWORD=$DB_PASSWORD
DB_NAME=nandailseba_db
DB_CONNECTION_LIMIT=10

# Firebase Configuration (You need to add your credentials)
FIREBASE_CREDENTIALS_PATH=./firebase-credentials.json
FIREBASE_PROJECT_ID=your-project-id

# Storage Configuration
UPLOAD_DIR=./storage/uploads
MAX_FILE_SIZE=5242880
ALLOWED_FILE_TYPES=jpg,jpeg,png,gif,webp

# API Configuration
API_BASE_URL=http://$(curl -s ifconfig.me):3000
FRONTEND_URL=*

# Security
JWT_SECRET=$(openssl rand -base64 32)
CORS_ORIGIN=*

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# Logging
LOG_LEVEL=info
EOF

print_success "Environment file created"

print_info "Step 10/10: Running Database Migrations"
npm run migrate
print_success "Database tables created"

print_info "Starting Application with PM2"
pm2 start src/index.js --name nandailseba-api
pm2 startup
pm2 save
print_success "Application started"

# Install and configure Nginx (optional but recommended)
print_info "Bonus: Installing Nginx (Web Server)"
apt-get install -y nginx

# Create Nginx config
cat > /etc/nginx/sites-available/nandailseba << 'EOF'
server {
    listen 80;
    server_name _;

    # Increase upload size
    client_max_body_size 10M;

    # API
    location /api/ {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Uploaded images
    location /uploads/ {
        alias /var/www/nandailseba-backend/storage/uploads/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Root
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
EOF

# Enable site
ln -sf /etc/nginx/sites-available/nandailseba /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Test and restart Nginx
nginx -t && systemctl restart nginx
systemctl enable nginx

print_success "Nginx configured"

# Configure Firewall
print_info "Configuring Firewall"
ufw allow 22/tcp    # SSH
ufw allow 80/tcp    # HTTP
ufw allow 443/tcp   # HTTPS (for future SSL)
ufw --force enable
print_success "Firewall configured"

# Save credentials to file
CREDS_FILE="/root/nandailseba-credentials.txt"
cat > $CREDS_FILE << EOF
=====================================
Nandail Seba Backend - Credentials
=====================================

MySQL Root Password: $MYSQL_ROOT_PASSWORD
Database User: nandailseba_user
Database Password: $DB_PASSWORD
Database Name: nandailseba_db

Application Directory: $APP_DIR
Server IP: $(curl -s ifconfig.me)

API Base URL: http://$(curl -s ifconfig.me)/api/v1
Health Check: http://$(curl -s ifconfig.me)/api/v1/health
Image Upload: http://$(curl -s ifconfig.me)/api/v1/images/upload-image

PM2 Commands:
  - pm2 status              (Check status)
  - pm2 logs                (View logs)
  - pm2 restart all         (Restart app)
  - pm2 stop all            (Stop app)

Nginx Commands:
  - systemctl status nginx  (Check status)
  - systemctl restart nginx (Restart)
  - nano /etc/nginx/sites-available/nandailseba (Edit config)

IMPORTANT:
1. Upload firebase-credentials.json to: $APP_DIR
2. Update FIREBASE_PROJECT_ID in: $APP_DIR/.env
3. After uploading Firebase file, restart: pm2 restart all

=====================================
EOF

chmod 600 $CREDS_FILE

echo ""
echo "======================================================"
print_success "🎉 Setup Complete!"
echo "======================================================"
echo ""
print_info "Your credentials are saved in: $CREDS_FILE"
echo ""
echo "📋 Important Information:"
echo "   API URL: http://$(curl -s ifconfig.me)/api/v1"
echo "   Health: http://$(curl -s ifconfig.me)/api/v1/health"
echo ""
echo "⚠️  Next Steps:"
echo "   1. Upload firebase-credentials.json to: $APP_DIR"
echo "   2. Edit .env file: nano $APP_DIR/.env"
echo "   3. Update FIREBASE_PROJECT_ID"
echo "   4. Restart app: pm2 restart all"
echo ""
echo "📝 View credentials: cat $CREDS_FILE"
echo "📊 Check status: pm2 status"
echo "📜 View logs: pm2 logs"
echo ""
print_success "Setup completed successfully!"
echo ""
