name: build-and-deploy

on:
  push:
    branches: [ main ]

jobs:
#───────────────── build, push & deploy (unified) ─────────────────
  build-and-deploy:
    runs-on: docker
    env:
      REG: ${{ vars.REGISTRY_URL }}
      REPO_OWNER: ${{ github.repository_owner }}
      APP_NAME: radiusnucleo
      APP_DOMAIN: wifi.nucleoriofrio.com
      # Variables sensibles de entorno desde secrets
      RADIUS_CLIENTS_CIDR: ${{ secrets.RADIUS_CLIENTS_CIDR }}
      RADIUS_SHARED_SECRET: ${{ secrets.RADIUS_SHARED_SECRET }}
    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 radiusnucleo (with SPA)
        run: |
          docker build -t $REG/$REPO_OWNER/radiusnucleo:${{ github.sha }} -t $REG/$REPO_OWNER/radiusnucleo:latest -f node-api/Dockerfile .
          docker push $REG/$REPO_OWNER/radiusnucleo:${{ github.sha }}
          docker push $REG/$REPO_OWNER/radiusnucleo:latest

      - name: Build+push radiusnucleo-freeradius
        run: |
          docker build -t $REG/$REPO_OWNER/radiusnucleo-freeradius:${{ github.sha }} -t $REG/$REPO_OWNER/radiusnucleo-freeradius:latest ./freeradius
          docker push $REG/$REPO_OWNER/radiusnucleo-freeradius:${{ github.sha }}
          docker push $REG/$REPO_OWNER/radiusnucleo-freeradius:latest

      - name: Info about environment
        run: |
          echo "ℹ️  Deploying $APP_NAME"
          echo "   Domain: $APP_DOMAIN"
          echo "   Image Node: $REG/$REPO_OWNER/radiusnucleo:latest"
          echo "   Image FreeRADIUS: $REG/$REPO_OWNER/radiusnucleo-freeradius:latest"
          echo "   Networks: principal, radiusnucleo_radius_net"

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

      - name: Pull fresh images used in compose
        env:
          RADIUS_CLIENTS_CIDR: ${{ secrets.RADIUS_CLIENTS_CIDR }}
          RADIUS_SHARED_SECRET: ${{ secrets.RADIUS_SHARED_SECRET }}
        run: docker compose pull

      - name: Clean up stack
        env:
          RADIUS_CLIENTS_CIDR: ${{ secrets.RADIUS_CLIENTS_CIDR }}
          RADIUS_SHARED_SECRET: ${{ secrets.RADIUS_SHARED_SECRET }}
        run: docker compose --project-name $APP_NAME down

      - name: Update stack
        env:
          RADIUS_CLIENTS_CIDR: ${{ secrets.RADIUS_CLIENTS_CIDR }}
          RADIUS_SHARED_SECRET: ${{ secrets.RADIUS_SHARED_SECRET }}
        run: docker compose --project-name $APP_NAME up -d --remove-orphans --wait
