#!/usr/bin/env bash
set -euo pipefail

# ─── Config ───
HOST="opticas-dev"           # sistematlan.icu
REMOTE_DIR="www/dev-opticasorlando.sistematlan.com"
BRANCH="development"

# ─── Colors ───
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${CYAN}━━━ Deploy Opticas Dev ━━━${NC}"
echo ""

# 1. El árbol debe estar limpio
if ! git diff --quiet HEAD 2>/dev/null; then
    echo -e "${YELLOW}⚠  Hay cambios sin commitear localmente${NC}"
    echo "   Haz commit antes de deploy."
    exit 1
fi

LOCAL_REV=$(git rev-parse --short HEAD)
echo -e "  Local:  ${GREEN}${BRANCH}${NC} @ ${LOCAL_REV}"

# 2. Push a origin si hay commits pendientes
AHEAD=$(git rev-list --count origin/${BRANCH}..${BRANCH} 2>/dev/null || echo "0")
if [ "$AHEAD" -gt 0 ]; then
    echo -e "  ${YELLOW}Pushing ${AHEAD} commit(s) to origin...${NC}"
    git push origin ${BRANCH}
fi

# 3. Deploy en el remoto.
#    composer y las migraciones corren AQUÍ, contra la base del servidor.
#    Antes se ejecutaban en la máquina local, cuyo .env apunta al Docker de
#    desarrollo: el servidor nunca se migraba.
echo ""
echo -e "  ${CYAN}Conectando a ${HOST}...${NC}"

ssh ${HOST} bash -s <<REMOTE
    set -euo pipefail
    cd ~/${REMOTE_DIR}

    echo "  Remote: \$(pwd)"
    echo "  Branch: \$(git branch --show-current)"

    git fetch origin ${BRANCH} --quiet
    BEHIND=\$(git rev-list --count HEAD..origin/${BRANCH})

    if [ "\$BEHIND" -eq 0 ]; then
        echo "  Ya está actualizado."
    else
        echo "  Pulling \${BEHIND} commit(s)..."
        git pull origin ${BRANCH} --quiet
        echo "  Deployed @ \$(git rev-parse --short HEAD)"
    fi

    echo ""
    echo "  Dependencias..."
    composer install --no-dev --optimize-autoloader --no-interaction --quiet

    # Optimize.php cachea las clases de Config; hay que invalidarlo tras el pull.
    rm -f writable/cache/*FactoriesCache* writable/cache/*FileLocatorCache* 2>/dev/null || true

    echo "  Migraciones..."
    php spark migrate 2>&1 | grep -E "Running:|Migrations complete|No new migrations" || true
REMOTE

echo ""
echo -e "${GREEN}━━━ Deploy completado ━━━${NC}"
