stages:
    - test
    - lint
    - build

run_tests:
    stage: test
    image: python:3.12
    variables:
        DJANGO_SECRET_KEY: 'random_secret_key_for_ci'
    before_script:
        - python -m pip install --upgrade pip
        - pip install --no-cache-dir -r requirements/django.txt
    script:
        - python manage.py test --verbosity=2
    rules:
        - if: $CI_COMMIT_BRANCH == "main"

check_node_syntax:
    stage: lint
    image: node:20-alpine
    before_script:
        - cd site
        - npm ci
    script:
        - npm run type-check
    rules:
        - if: $CI_COMMIT_BRANCH == "main"

build_and_push:
    stage: build
    image: docker:24.0.7
    variables:
        DOCKER_HOST: tcp://docker:2375
        DOCKER_TLS_CERTDIR: ''
    services:
        - name: docker:24.0.7-dind
          alias: docker
          command: ['--tls=false', '--host=tcp://0.0.0.0:2375']
    before_script:
        - apk add --no-cache git
    script:
        - echo "Waiting for Docker daemon..."
        - for i in $(seq 1 30); do docker info && break || sleep 1; done
        - echo "Logging in to registry ${REGISTRY_URL}"
        - echo "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USERNAME" --password-stdin "$REGISTRY_URL"
        - export DJANGO_IMAGE_NAME="${REGISTRY_URL}/${DJANGO_IMAGE_PATH}:${IMAGE_TAG}"
        - echo "Building image ${DJANGO_IMAGE_NAME}"
        - docker build -t "$DJANGO_IMAGE_NAME" -f ./compose/prod/django/Dockerfile --no-cache .
        - echo "Pushing image ${DJANGO_IMAGE_NAME}"
        - docker push "$DJANGO_IMAGE_NAME"
        - export CELERY_IMAGE_NAME="${REGISTRY_URL}/${CELERY_IMAGE_PATH}:${IMAGE_TAG}"
        - echo "Building Celery image ${CELERY_IMAGE_NAME}"
        - docker build -t "$CELERY_IMAGE_NAME" -f ./compose/prod/celery/Dockerfile --no-cache .
        - echo "Pushing Celery image ${CELERY_IMAGE_NAME}"
        - docker push "$CELERY_IMAGE_NAME"
    needs:
        - job: run_tests
          optional: true
