name: build-and-deploy

on:
  push:
    branches: [ main, master ]

jobs:
  build-and-deploy:
    runs-on: docker
    env:
      REG: ${{ vars.REGISTRY_URL }}
      REPO_OWNER: ${{ github.repository_owner }}
      APP_NAME: ${{ vars.APP_NAME }}
      APP_DOMAIN: ${{ vars.APP_DOMAIN }}
      NUXT_PUBLIC_APP_URL: ${{ vars.NUXT_PUBLIC_APP_URL }}
      POSTGRES_DB: ${{ vars.POSTGRES_DB }}
      POSTGRES_USER: ${{ vars.POSTGRES_USER }}
      POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
    steps:
      - name: Checkout del repositorio
        uses: actions/checkout@v4

      - name: Build, push y deploy completo
        run: |
          set -e

          echo "🔐 Login al registry..."
          docker login ${{ vars.REGISTRY_URL }} -u ${{ secrets.REGISTRY_USERNAME }} -p ${{ secrets.REGISTRY_PASSWORD }}

          echo "🏗️  Construyendo imagen de Nuxt..."
          docker build -t $REG/$REPO_OWNER/$APP_NAME:${{ github.sha }} -t $REG/$REPO_OWNER/$APP_NAME:latest ./nuxt4

          echo "📤 Subiendo imágenes..."
          docker push $REG/$REPO_OWNER/$APP_NAME:${{ github.sha }}
          docker push $REG/$REPO_OWNER/$APP_NAME:latest

          echo "ℹ️  Información de despliegue:"
          echo "   App: $APP_NAME"
          echo "   Domain: $APP_DOMAIN"
          echo "   Image: $REG/$REPO_OWNER/$APP_NAME:latest"
          echo "   Networks: principal, traefik-network"

          echo "🔄 Descargando imágenes actualizadas..."
          docker compose pull

          echo "🧹 Limpiando stack anterior..."
          docker compose --project-name $APP_NAME down

          echo "🚀 Desplegando stack actualizado..."
          docker compose --project-name $APP_NAME up -d --remove-orphans --wait

          echo "✅ Despliegue completado exitosamente!"
