name: build-and-push

on:
  push:
    branches: [ main ]

jobs:
  build:
    runs-on: docker
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Login to registry
        uses: docker/login-action@v2
        with:
          registry: gitea.interno.com
          username: nucleo000
          password: 7bc7b2fcd283bd6a251bef3ede368b7f897c919d

      - name: Build root image
        run: |
          docker build -f ./Dockerfile \
            -t gitea.interno.com/nucleo000/planilla:${{ github.sha }} \
            -t gitea.interno.com/nucleo000/planilla:latest .

      - name: Build API image
        run: |
          docker build -f ./api/Dockerfile \
            -t gitea.interno.com/nucleo000/planilla-api:${{ github.sha }} \
            -t gitea.interno.com/nucleo000/planilla-api:latest \
            ./api

      - name: Build UI image
        run: |
          docker build -f ./ui/Dockerfile \
            -t gitea.interno.com/nucleo000/planilla-ui:${{ github.sha }} \
            -t gitea.interno.com/nucleo000/planilla-ui:latest \
            ./ui

      - name: Push images
        run: |
          for img in planilla planilla-api planilla-ui; do
            docker push gitea.interno.com/nucleo000/$img:${{ github.sha }}
            docker push gitea.interno.com/nucleo000/$img:latest
          done

  deploy:
    runs-on: docker
    needs: build
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Login to registry
        run: |
          echo "Logging into registry…"
          docker login gitea.interno.com -u nucleo000 -p 7bc7b2fcd283bd6a251bef3ede368b7f897c919d

      - name: Pull latest images
        run: |
          docker pull gitea.interno.com/nucleo000/planilla:latest
          docker pull gitea.interno.com/nucleo000/planilla-api:latest
          docker pull gitea.interno.com/nucleo000/planilla-ui:latest

      - name: Teardown previous stack
        run: docker compose down --remove-orphans || true

      - name: Start all services fresh
        run: docker compose up -d --build --force-recreate --remove-orphans
