#!/bin/bash
set -e

echo "============================================"
echo "  Moro - Docker Entrypoint"
echo "============================================"

# -----------------------------------------------
# 0. Read env vars from .env file (safe parsing)
# -----------------------------------------------
get_env() {
    local key="$1"
    local default="$2"
    if [ -f ".env" ]; then
        local val
        val=$(grep "^${key}=" .env | head -1 | cut -d'=' -f2- | sed 's/\r$//')
        if [ -n "$val" ]; then
            echo "$val"
            return
        fi
    fi
    echo "$default"
}

DB_HOST=$(get_env "DB_HOST" "mysql")
DB_PORT=$(get_env "DB_PORT" "3306")
DB_DATABASE=$(get_env "DB_DATABASE" "moro")
DB_PASSWORD=$(get_env "DB_PASSWORD" 'abc1234$')

echo "==> DB config: host=${DB_HOST}, port=${DB_PORT}, database=${DB_DATABASE}"

# -----------------------------------------------
# 1. Wait for MySQL
# -----------------------------------------------
echo "==> Waiting for MySQL at ${DB_HOST}:${DB_PORT}..."
max_wait=120
counter=0
while ! nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null; do
    counter=$((counter + 1))
    if [ $counter -ge $max_wait ]; then
        echo "ERROR: MySQL not ready after ${max_wait}s"
        exit 1
    fi
    sleep 1
done
echo "==> MySQL is ready!"

# -----------------------------------------------
# 2. Wait for SQL import on first run
# -----------------------------------------------
echo "==> Checking database tables..."
for i in $(seq 1 300); do
    TABLE_COUNT=$(mysql --skip-ssl -h"$DB_HOST" -uroot -p"$DB_PASSWORD" "$DB_DATABASE" -N -e \
        "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='${DB_DATABASE}';" 2>/dev/null || echo "0")
    if [ "$TABLE_COUNT" != "0" ] && [ "$TABLE_COUNT" -gt 10 ] 2>/dev/null; then
        echo "==> Database ready! ($TABLE_COUNT tables found)"
        break
    fi
    if [ $i -eq 1 ]; then
        echo "==> Waiting for SQL import to complete (this may take a few minutes on first run)..."
    fi
    if [ $((i % 30)) -eq 0 ]; then
        echo "    ... still waiting ($i seconds)"
    fi
    sleep 1
done

# -----------------------------------------------
# 3. Git safe directory
# -----------------------------------------------
git config --global --add safe.directory /var/www 2>/dev/null || true
git config --global url."https://github.com/".insteadOf "git://github.com/" 2>/dev/null || true

# -----------------------------------------------
# 4. Composer install
# -----------------------------------------------
if [ ! -f "vendor/autoload.php" ]; then
    echo "==> Installing Composer dependencies..."
    composer install --no-interaction --optimize-autoloader
else
    echo "==> Composer dependencies already installed, skipping."
fi

# -----------------------------------------------
# 5. App key
# -----------------------------------------------
if grep -q "^APP_KEY=$" .env 2>/dev/null; then
    echo "==> Generating application key..."
    php artisan key:generate --force
else
    echo "==> App key already set, skipping."
fi

# -----------------------------------------------
# 6. Storage link
# -----------------------------------------------
if [ ! -L "public/storage" ]; then
    echo "==> Creating storage symlink..."
    php artisan storage:link 2>/dev/null || true
fi

# -----------------------------------------------
# 7. Run pending migrations (after SQL import)
# -----------------------------------------------
echo "==> Running pending migrations..."
php artisan migrate --force 2>&1 || true

# -----------------------------------------------
# 8. Clear caches
# -----------------------------------------------
echo "==> Clearing caches..."
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear 2>/dev/null || true

# -----------------------------------------------
# 9. NPM install + build (non-blocking)
# -----------------------------------------------
if [ ! -d "node_modules/vue" ]; then
    echo "==> Installing npm dependencies..."
    for attempt in 1 2 3; do
        npm install 2>&1 && break
        echo "==> npm install failed (attempt $attempt/3), retrying..."
        npm cache clean --force 2>/dev/null
        sleep 2
    done
fi

if [ ! -f "public/js/app.js" ] || [ ! -f "public/backend/js/admin.js" ]; then
    echo "==> Building frontend assets..."
    npm run dev-all 2>&1 || echo "WARNING: Frontend build failed. Run 'npm run dev-all' manually inside container."
fi

# -----------------------------------------------
# Done - start app
# -----------------------------------------------
echo "============================================"
echo "  Moro is starting on http://localhost:8000"
echo "============================================"
exec "$@"
