#!/bin/bash

echo "🚀 Running initial setup..."

# Ensure .env exists
if [ -f ".env" ]; then
    # Extract APP_ENV (strip quotes if present)
    APP_ENV=$(grep '^APP_ENV=' .env | cut -d '=' -f2-)
    APP_ENV=$(echo "$APP_ENV" | tr -d '\r' | tr -d '"' | tr -d '\\' | tr -d '\n' | xargs)
else
    echo "❌ .env file not found. You should create it before running setup."
    exit 1
    APP_ENV=production
fi

# Default fallback if still empty
if [ -z "$APP_ENV" ]; then
    APP_ENV=production
fi

echo "🌍 APP_ENV: $APP_ENV"

# Ensure necessary directories exist
echo "📂 Creating storage and logs folders..."
mkdir -p storage/framework/{cache,sessions,views} storage/logs storage/framework/cache/data

# Seed uploads folder if it exists
if [ -d "uploads_seeder" ]; then
    echo "📁 Seeding uploads folder..."
    rm -rf uploads  # Ensure it's clean
    mv uploads_seeder uploads
else
    echo "⚠️ WARNING: uploads_seeder folder not found. Skipping..."
fi

# Install Composer dependencies conditionally
if [ ! -d "vendor" ]; then
    echo "📦 Installing Composer dependencies..."

    if [ "$APP_ENV" = "local" ] || [ "$APP_ENV" = "staging" ]; then
        composer install --prefer-dist --optimize-autoloader --no-interaction
    else
        composer install --prefer-dist --no-dev --optimize-autoloader --no-interaction
    fi
else
    echo "✅ Composer dependencies already installed. Skipping..."
fi

# Generate APP_KEY if missing
if ! grep -qE "^APP_KEY=.{32,}" .env; then
    echo "🔑 APP_KEY is missing or too short. Generating..."
    php artisan key:generate
else
    echo "✅ APP_KEY exists."
fi

# Clear Laravel caches
echo "🧹 Clearing Laravel cache and compiled files..."
php artisan optimize:clear
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

echo "🧬 Running migrations..."
php artisan migrate --force

echo "🌱 Seeding database..."
php artisan db:seed --force

echo "🔐 Running encryption tasks..."
php artisan encryption:run

echo "⏰ Installing cron jobs..."
if [ -f "crons.sh" ]; then
    sh crons.sh | crontab -
    echo "✅ Cron installed."
else
    echo "⚠️ crons.sh not found. Skipping cron setup..."
fi

# Check for node_modules
if [ ! -d "node_modules" ]; then
    echo "📦 Installing frontend assets..."
    npm install --no-audit --no-fund
else
    echo "✅ Node modules already installed. Skipping..."
fi

echo "🎛️ Building frontend..."
npm run build  # or use `build` in production

# Media manager assets
echo "📂 Publishing media manager assets..."
php artisan vendor:publish --tag=media-manager --force

echo "✅ All setup steps completed successfully."
