name: Build and Push Docker Image

on:
  push:
    branches:
      - development
      - latest

jobs:
  test:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Checkout del código
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
      - name: Configurar Python
        uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
        with:
          python-version: '3.14'
      - name: Configurar uv
        uses: astral-sh/setup-uv@d0d8abe699bfb85fec6de9f7adb5ae17292296ff # v6
      - name: Instalar dependencias
        run: |
          uv sync --no-dev --no-install-project
      - name: Ejecutar tests
        env:
          DJANGO_SETTINGS_MODULE: proyecto.settings
        run: |
          SECRET_KEY=donotusethisinproductionitisunsafe uv 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6

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

      - name: Login en GHCR
        uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # 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@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
        with:
          context: .
          push: true
          # Sanitizamos el nombre de la rama (reemplazamos / por -)
          tags: ghcr.io/dsaub/proyecto-mvc:${{ env.IMAGE_TAG }}
