name: build-and-deploy

on:
  push:
    branches: [ main ]

jobs:
#───────────────── build & push imagen única ─────────────────
  build:
    runs-on: docker
    env:
      REG: gitea.nucleoriofrio.com/nucleo000
    steps:
      - uses: actions/checkout@v3
      - uses: docker/setup-buildx-action@v2
      - uses: docker/login-action@v2
        with:
          registry: gitea.nucleoriofrio.com
          username: nucleo000
          password: 7bc7b2fcd283bd6a251bef3ede368b7f897c919d

      - name: Build and push snatchgame
        run: |
          docker build -f deploy/Dockerfile -t $REG/snatchgame:${{ github.sha }} -t $REG/snatchgame:latest .
          docker push $REG/snatchgame:${{ github.sha }}
          docker push $REG/snatchgame:latest

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

      - name: Stop existing container
        run: docker stop snatchgame || true

      - name: Remove existing container
        run: docker rm snatchgame || true

      - name: Pull latest image
        run: docker pull $REG/snatchgame:latest

      - name: Run new container
        run: |
          docker run -d \
            --name snatchgame \
            --restart unless-stopped \
            --network principal \
            $REG/snatchgame:latest