name: deploy-analiticaNucleo

on:
  push:
    branches: [ master ]

jobs:
  #───────────────── deploy ─────────────────
  deploy:
    runs-on: docker
    env:
      SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
      SUPABASE_ANON_KEY: ${{ secrets.SUPABASE_ANON_KEY }}
    steps:
      - uses: actions/checkout@v3

      - name: Create .env file from secrets
        run: |
          cat > .env << EOF
          SUPABASE_URL=${{ secrets.SUPABASE_URL }}
          SUPABASE_ANON_KEY=${{ secrets.SUPABASE_ANON_KEY }}
          EOF

      - name: Ensure external docker network exists
        run: |
          docker network inspect principal >/dev/null 2>&1 || docker network create principal

      - name: Stop existing analiticanucleo stack
        run: docker compose -f docker-compose.yml --project-name analiticanucleo down || true

      - name: Pull latest images (if any)
        run: docker compose -f docker-compose.yml pull || true

      - name: Build and start analiticanucleo stack
        run: docker compose -f docker-compose.yml --project-name analiticanucleo up -d --build --remove-orphans

      - name: Wait for service to be ready
        run: |
          echo "Waiting for Nuxt app to start..."
          sleep 10
          docker compose -f docker-compose.yml --project-name analiticanucleo logs --tail=30 nuxt-app

      - name: Show service status
        run: docker compose -f docker-compose.yml --project-name analiticanucleo ps

      - name: Show recent logs
        run: docker compose -f docker-compose.yml --project-name analiticanucleo logs --tail=50

      - name: Test service health
        run: |
          echo "Checking container health..."
          CID=$(docker compose -f docker-compose.yml --project-name analiticanucleo ps -q nuxt-app)
          echo "Container: $CID"
          docker inspect "$CID" --format '{{.State.Status}}' || true
