name: build-and-deploy

on:
  push:
    branches: [ main ]

jobs:
#───────────────── filtra qué dirs cambiaron ─────────────────
  filter:
    runs-on: docker
    outputs:
      server: ${{ steps.paths.outputs.server }}
      client: ${{ steps.paths.outputs.client }}
      admin:  ${{ steps.paths.outputs.admin }}
    steps:
      - uses: actions/checkout@v3
      - id: paths
        uses: dorny/paths-filter@v3
        with:
          filters: |
            server: "server/**"
            client: "client/**"
            admin:  "admin/**"

#───────────────── build & push ─────────────────
  build:
    needs: filter
    runs-on: docker
    env:
      REG: gitea.interno.com/nucleo000
    steps:
      - uses: actions/checkout@v3
      - uses: docker/setup-buildx-action@v2
      - uses: docker/login-action@v2
        with:
          registry: gitea.interno.com
          username: nucleo000           # ⬅ ponelo en secrets
          password: 7bc7b2fcd283bd6a251bef3ede368b7f897c919d # ⬅ idem

      - name: Build+push server
        if: needs.filter.outputs.server == 'true'
        run: |
          docker build -f server/Dockerfile -t $REG/snatchgame-server:${{ github.sha }} -t $REG/snatchgame-server:latest server
          docker push $REG/snatchgame-server:${{ github.sha }}
          docker push $REG/snatchgame-server:latest

      - name: Build+push client
        if: needs.filter.outputs.client == 'true'
        run: |
          docker build -f client/Dockerfile -t $REG/snatchgame-client:${{ github.sha }} -t $REG/snatchgame-client:latest client
          docker push $REG/snatchgame-client:${{ github.sha }}
          docker push $REG/snatchgame-client:latest

      - name: Build+push admin
        if: needs.filter.outputs.admin == 'true'
        run: |
          docker build -f admin/Dockerfile -t $REG/snatchgame-admin:${{ github.sha }} -t $REG/snatchgame-admin:latest admin
          docker push $REG/snatchgame-admin:${{ github.sha }}
          docker push $REG/snatchgame-admin:latest

#───────────────── deploy ─────────────────
  deploy:
    needs: build
    runs-on: docker
    env:
      REG: gitea.interno.com/nucleo000
    steps:
      - uses: actions/checkout@v3
      - name: Login to registry
        run: docker login gitea.interno.com -u nucleo000 -p 7bc7b2fcd283bd6a251bef3ede368b7f897c919d

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

      - name: Clean up stack
        run: docker compose --project-name snatchgame down

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