name: build-and-deploy

on:
  push:
    branches: [ main, master ]

jobs:
#───────────────── build & push ─────────────────
  build:
    runs-on: docker
    env:
      REG: ${{ vars.REGISTRY_URL }}
      APP_NAME: ${{ vars.APP_NAME }}
    steps:
      - uses: actions/checkout@v3
      - uses: docker/setup-buildx-action@v2
      - uses: docker/login-action@v2
        with:
          registry: ${{ vars.REGISTRY_URL }}
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Build+push ${{ vars.APP_NAME }}
        run: |
          cd nuxt4-app
          docker build -t $REG/${{ github.repository_owner }}/$APP_NAME:${{ github.sha }} -t $REG/${{ github.repository_owner }}/$APP_NAME:latest .
          docker push $REG/${{ github.repository_owner }}/$APP_NAME:${{ github.sha }}
          docker push $REG/${{ github.repository_owner }}/$APP_NAME:latest

#───────────────── deploy ─────────────────
  deploy:
    needs: build
    runs-on: docker
    env:
      REG: ${{ vars.REGISTRY_URL }}
      REPO_OWNER: ${{ github.repository_owner }}
      APP_NAME: ${{ vars.APP_NAME }}
      APP_DOMAIN: ${{ vars.APP_DOMAIN }}
      # Variables sensibles de entorno desde secrets
      SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
      SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.SUPABASE_SERVICE_ROLE_KEY }}
      SUPABASE_ANON_KEY: ${{ secrets.SUPABASE_ANON_KEY }}
      # Variables públicas desde vars
      NUXT_PUBLIC_AUTHENTIK_URL: ${{ vars.NUXT_PUBLIC_AUTHENTIK_URL }}
      # Metabase configuration
      METABASE_URL: ${{ vars.METABASE_URL }}
      METABASE_API_KEY: ${{ secrets.METABASE_API_KEY }}
      METABASE_EMAIL: ${{ secrets.METABASE_EMAIL }}
      METABASE_PASSWORD: ${{ secrets.METABASE_PASSWORD }}
    steps:
      - uses: actions/checkout@v3
      - name: Login to registry
        run: docker login ${{ vars.REGISTRY_URL }} -u ${{ secrets.REGISTRY_USERNAME }} -p ${{ secrets.REGISTRY_PASSWORD }}

      - name: Info about environment
        run: |
          echo "ℹ️  Deploying ${{ vars.APP_NAME }}"
          echo "   Domain: ${{ vars.APP_DOMAIN }}"
          echo "   Image: ${{ vars.REGISTRY_URL }}/${{ github.repository_owner }}/${{ vars.APP_NAME }}:latest"
          echo "   Network: principal"

      - name: Pull fresh images used in compose
        run: docker compose pull

      - name: Clean up stack
        run: docker compose --project-name $APP_NAME down

      - name: Update stack
        run: docker compose --project-name $APP_NAME up -d --remove-orphans --wait
