name: Build and Push Docker Image

on:
  push:
    branches:
      - development
      - latest

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout del código
        uses: actions/checkout@v6
      - name: Configurar Python
        uses: actions/setup-python@v6
        with:
          python-version: '3.14'
      - name: Instalar dependencias
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
      - name: Ejecutar tests
        env:
          DJANGO_SETTINGS_MODULE: proyecto.settings
        run: |
          python manage.py test
  docker:
    runs-on: ubuntu-latest
    needs: test
    permissions:
      contents: read
      packages: write # Necesario para subir a GHCR

    steps:
      - name: Checkout del código
        uses: actions/checkout@v6

      - name: Configurar Docker Buildx
        uses: docker/setup-buildx-action@v4

      - name: Login en GHCR
        uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Preparar tag de imagen
        run: |
          TAG=$(echo "${{ github.ref_name }}" | sed 's/\//-/g')
          echo "IMAGE_TAG=$TAG" >> $GITHUB_ENV

      - name: Build y Push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          # Sanitizamos el nombre de la rama (reemplazamos / por -)
          tags: ghcr.io/dsaub/proyecto-mvc:${{ env.IMAGE_TAG }}
