#!/usr/bin/env bash
# ============================================================
#  NexSMS — Build Script
#  Produces: bulk-sms-platform.zip
#
#  Usage:
#    chmod +x build-zip.sh
#    ./build-zip.sh
#
#  The zip will be created in the project root (same directory
#  as this script).
# ============================================================
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$SCRIPT_DIR"
OUT_ZIP="$SCRIPT_DIR/../bulk-sms-platform.zip"
TMP_DIR="/tmp/nexsms_build_$$"

echo "=================================================="
echo "  NexSMS Build Script"
echo "=================================================="
echo "Project : $PROJECT_DIR"
echo "Output  : $OUT_ZIP"
echo ""

# ── 1. Composer install (production) ──────────────────────
echo "[1/5] Running composer install --no-dev..."
cd "$PROJECT_DIR"
composer install --no-dev --optimize-autoloader --quiet
echo "      Done."

# ── 2. Copy project to temp dir ───────────────────────────
echo "[2/5] Preparing build directory..."
rm -rf "$TMP_DIR"
mkdir -p "$TMP_DIR/bulk-sms-platform"

rsync -a --exclude='.git' \
         --exclude='.env' \
         --exclude='build-zip.sh' \
         --exclude='tests/' \
         --exclude='phpunit.xml.dist' \
         --exclude='*.log' \
         --exclude='writable/cache/*' \
         --exclude='writable/logs/*' \
         --exclude='writable/session/*' \
         --exclude='writable/uploads/*' \
         --exclude='writable/debugbar/*' \
         "$PROJECT_DIR/" "$TMP_DIR/bulk-sms-platform/"

# ── 3. Strip dev-only vendor files ────────────────────────
echo "[3/5] Stripping dev files..."
rm -rf "$TMP_DIR/bulk-sms-platform/vendor/fakerphp" 2>/dev/null || true

# ── 4. Recreate writable structure ───────────────────────
echo "[4/5] Creating writable directory structure..."
for DIR in cache logs session uploads debugbar; do
    mkdir -p "$TMP_DIR/bulk-sms-platform/writable/$DIR"
    touch "$TMP_DIR/bulk-sms-platform/writable/$DIR/.gitkeep"
done

# ── 5. Create ZIP ─────────────────────────────────────────
echo "[5/5] Creating zip archive..."
cd "$TMP_DIR"
zip -r "$OUT_ZIP" bulk-sms-platform/ -q
rm -rf "$TMP_DIR"

echo ""
echo "=================================================="
echo "  Build complete!"
echo "  Archive: $OUT_ZIP"
echo "  Size   : $(du -sh "$OUT_ZIP" | cut -f1)"
echo "=================================================="
echo ""
echo "Next steps:"
echo "  1. Upload bulk-sms-platform.zip to your server"
echo "  2. Extract: unzip bulk-sms-platform.zip"
echo "  3. Follow DEPLOYMENT.md for setup instructions"
echo ""
