name: Verificar versión, Compilar y Desplegar

on:
  push:
    branches:
      - main
    paths:
      - 'package.json'

jobs:
  check-version:
    runs-on: ubuntu-latest
    outputs:
      version_changed: ${{ steps.compare_versions.outputs.version_changed }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          fetch-depth: 2

      - name: Obtener versión del package.json
        run: |
          git show HEAD:package.json > current_package.json
          git show HEAD~1:package.json > previous_package.json

      - name: Comparar versiones del proyecto
        id: compare_versions
        run: |
          current_version=$(jq -r .version current_package.json)
          previous_version=$(jq -r .version previous_package.json)
          if [ "$current_version" != "$previous_version" ]; then
            echo "Versión cambiada de $previous_version a $current_version"
            echo "version_changed=true" >> $GITHUB_OUTPUT
          else
            echo "La versión no ha cambiado"
            echo "version_changed=false" >> $GITHUB_OUTPUT
          fi

  build:
    needs: check-version
    if: needs.check-version.outputs.version_changed == 'true'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '22' # Ajusta a la versión de Node.js que necesites

      - name: Instalar Dependencias
        run: npm ci

      - name: Compilar
        run: npm run build

      - name: Archivar build
        uses: actions/upload-artifact@v3
        with:
          name: dist
          path: dist

  deploy:
    needs: [check-version, build]
    if: needs.check-version.outputs.version_changed == 'true'
    runs-on: ubuntu-latest
    steps:
      - name: Descargar build
        uses: actions/download-artifact@v3
        with:
          name: dist
          path: dist

      - name: Instalar ssh
        run: |
          sudo apt-get update
          sudo apt-get install sshpass

      - name: Subir al servidor
        env:
          SERVER_IP: ${{ secrets.SERVER_IP }}
          SERVER_USER: ${{ secrets.SERVER_USER }}
          SERVER_PASS: ${{ secrets.SERVER_PASS }}
          DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
        run: |
          # Borra la copia anterior
          sshpass -p $SERVER_PASS ssh -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "rm -rf $DEPLOY_PATH/*"
          # Sube la nueva versión
          sshpass -p $SERVER_PASS scp -o StrictHostKeyChecking=no -r dist/* $SERVER_USER@$SERVER_IP:$DEPLOY_PATH