name: Build and Deploy

on:
  push:
    branches:
      - main

jobs:
  # ===================================================================
  # JOB 1: CONSTRUIR Y SUBIR LAS IMÁGENES (FUNCIONA PERFECTAMENTE)
  # ===================================================================
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Build Backend Image and Save as Tar
        run: |
          # ... (sin cambios aquí)

      - name: Build Frontend Image and Save as Tar
        run: |
          # ... (sin cambios aquí)

  # ===================================================================
  # JOB 2: DESPLEGAR LA APLICACIÓN (LA SOLUCIÓN DEFINITIVA)
  # ===================================================================
  deploy:
    runs-on: ubuntu-latest
    needs: build-and-push
    
    steps:
      - name: Deploy to Production via SSH
        run: |
          set -e

          # 1. Preparar el cliente SSH
          apt-get update > /dev/null && apt-get install -y openssh-client git > /dev/null
          mkdir -p ~/.ssh
          echo "${{ secrets.PROD_SERVER_SSH_KEY }}" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -H ${{ secrets.PROD_SERVER_HOST }} >> ~/.ssh/known_hosts
          
          # 2. Conectarse al HOST y ejecutar todo el proceso allí
          ssh ${{ secrets.PROD_SERVER_USER }}@${{ secrets.PROD_SERVER_HOST }} 'bash -s' \
            '${{ secrets.DB_SA_PASSWORD_SECRET }}' \
            '${{ secrets.JWT_KEY_SECRET }}' \
            << 'EOF'
              set -e

              # --- PARTE 1: PREPARACIÓN ---
              echo "--- (HOST) Preparing for deployment ---"
              DB_PASSWORD="$1"
              JWT_KEY="$2"

              # Nos movemos al directorio de la aplicación
              cd /opt/gestion-integral
              
              # --- PARTE 2: CREAR FICHERO .env TEMPORAL ---
              echo "--- (HOST) Creating temporary .env file ---"
              # Creamos un fichero .env que docker-compose leerá automáticamente.
              # Esto es más robusto que usar 'export'.
              echo "DB_SA_PASSWORD=${DB_PASSWORD}" > .env
              echo "JWT_KEY=${JWT_KEY}" >> .env

              # --- PARTE 3: DESPLEGAR ---
              echo "--- (HOST) Pulling and starting application... ---"
              # Ya no necesitamos 'export', docker-compose usará el .env
              docker compose pull
              docker compose up -d

              # --- PARTE 4: LIMPIEZA ---
              echo "--- (HOST) Cleaning up... ---"
              # Eliminamos el fichero .env para no dejar secretos en el disco.
              rm .env
              docker image prune -af
              
              echo "--- ¡¡DESPLIEGUE COMPLETADO Y VERIFICADO!! ---"
          EOF